Selasa, 30 Juni 2020

Upload And Load Image



package com.example.layanancomplain;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;


public class UploadToServer extends AppCompatActivity {
    String myip="", myFILE="",id_penugasan="";
    JSONParser jsonParser = new JSONParser();



    private static final int PICK_IMAGE = 1;
    private static final int PICK_Camera_IMAGE = 2;
    private ImageView imgView;
    private Button upload,cancel;
    private Bitmap bitmap;
    Uri imageUri;
    MediaPlayer mp=new MediaPlayer();

    String URL="",NFUpload="";
    TextView messageText;
    Button uploadButton,btnpilih,btncamera;
    int serverResponseCode = 0;
    ProgressDialog dialog = null;

    String upLoadServerUri = null;

    /**********  File Path *************/    final String uploadFilePath = "/mnt/sdcard/";
    String uploadFileName = "myfile.jpg";


    private static final int MY_PERMISSION_REQUEST = 1;

    @Override    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.uploadserver);


        if (ContextCompat.checkSelfPermission(UploadToServer.this,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(UploadToServer.this,
                    Manifest.permission.CAMERA)) {
                ActivityCompat.requestPermissions(UploadToServer.this,
                        new String[]{Manifest.permission.CAMERA}, MY_PERMISSION_REQUEST);
            } else {
                ActivityCompat.requestPermissions(UploadToServer.this,
                        new String[]{Manifest.permission.CAMERA}, MY_PERMISSION_REQUEST);
            }
        } else {
            //DO NOTHING        }



        Intent i = getIntent();
        id_penugasan = i.getStringExtra("pk");


        imgView = (ImageView) findViewById(R.id.imageView);
        uploadButton = (Button)findViewById(R.id.uploadButton);
        messageText  = (TextView)findViewById(R.id.messageText);

        btnpilih = (Button)findViewById(R.id.btnpilih);
        btncamera = (Button)findViewById(R.id.btncamera);

        messageText.setText(uploadFilePath+"/"+uploadFileName+"'");

        /************* Php script path ****************/        URL=jsonParser.getIP()+"uploadserver.php";
        upLoadServerUri =   URL;
        uploadButton.setOnClickListener(new OnClickListener() {
            @Override            public void onClick(View v) {

                dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true);

                new Thread(new Runnable() {
                    public void run() {
                        runOnUiThread(new Runnable() {
                            public void run() {
                               messageText.setText("uploading started.....");
                            }
                        });
                        String AL=messageText.getText().toString();
                        File f=new File(AL);
                        myFILE=f.getName();
                        uploadFiles(AL);

                       
                    }
                }).start();
                
                
              
            }
        });


        btnpilih.setOnClickListener(new OnClickListener() {
            @Override            public void onClick(View v) {
                try {
                    Intent gintent = new Intent();
                    gintent.setType("image/*");
                    gintent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(gintent, "Select Picture"),PICK_IMAGE);
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(),
                            e.getMessage(),
                            Toast.LENGTH_LONG).show();
                    Log.e(e.getClass().getName(), e.getMessage(), e);
                }
            }
        });


        btncamera.setOnClickListener(new OnClickListener() {
            @Override            public void onClick(View v) {
                //define the file-name to save photo taken by Camera activity                String fileName = "new-photo-name.jpg";
                //create parameters for Intent with filename                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.TITLE, fileName);
                values.put(MediaStore.Images.Media.DESCRIPTION,"Image captured by camera");
                //imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)                imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                //create new Intent                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                startActivityForResult(intent, PICK_Camera_IMAGE);
            }
        });
    }

    public int uploadFiles(String sourceFileUri) {
        String fileName = sourceFileUri;
        NFUpload=fileName;
        uploadFileName=NFUpload;
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);

        if (!sourceFile.isFile()) {

            dialog.dismiss();
            
            Log.d("uploadFile", "Source File not exist :"                    +uploadFilePath + "" + uploadFileName);

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("Source File not exist :"                            +uploadFilePath + "" + uploadFileName);
                }
            });

            return 0;

        }
        else        {
            try {

                // open a URL connection to the Servlet                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                URL url = new URL(upLoadServerUri);

                // Open a HTTP  connection to  the URL                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs                conn.setDoOutput(true); // Allow Outputs                conn.setUseCaches(false); // Don't use a Cached Copy                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", fileName);
              
                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""                        + fileName + "\"" + lineEnd);

                dos.writeBytes(lineEnd);

                // create a buffer of  maximum size                bytesAvailable = fileInputStream.available();

                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {

                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                }

                // send multipart form data necesssary after file data...                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                Log.i("uploadFile", "HTTP Response is : "                        + serverResponseMessage + ": " + serverResponseCode);

                if(serverResponseCode == 200){

                    runOnUiThread(new Runnable() {
                        public void run() {

                            String msg = "File Upload Completed:" + uploadFileName;

                            messageText.setText(msg);
                            Toast.makeText(UploadToServer.this, "File Upload Complete.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                //close the streams //                fileInputStream.close();
                dos.flush();
                dos.close();

                
                Intent i = new Intent(UploadToServer.this,Add_complain.class);
                i.putExtra("upload", myFILE);
                   startActivity(i); 
                   finish();
                   
                   
            } catch (MalformedURLException ex) {

                dialog.dismiss();
                ex.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("MalformedURLException Exception : check script url.");
                        Toast.makeText(UploadToServer.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                    }
                });

                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {

                dialog.dismiss();
                e.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("Got Exception : see logcat ");
                        Toast.makeText(UploadToServer.this, "Got Exception : see logcat ",
                                Toast.LENGTH_SHORT).show();
                    }
                });

            }
            dialog.dismiss();
            return serverResponseCode;

        } // End else block    }





    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Uri selectedImageUri = null;
        String filePath = null;
        switch (requestCode) {
            case PICK_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    selectedImageUri = data.getData();
                }
                break;
            case PICK_Camera_IMAGE:
                if (resultCode == RESULT_OK) {
                    //use imageUri here to access the image                    selectedImageUri = imageUri;
          /*Bitmap mPic = (Bitmap) data.getExtras().get("data");      selectedImageUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), mPic, getResources().getString(R.string.app_name), Long.toString(System.currentTimeMillis())));*/                } else if (resultCode == RESULT_CANCELED) {
                    Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
                }
                break;
        }

        if(selectedImageUri != null){
            try {
                // OI FILE Manager                String filemanagerstring = selectedImageUri.getPath();

                // MEDIA GALLERY                String selectedImagePath = getPath(selectedImageUri);

                   
                messageText.setText(selectedImagePath);


                if (selectedImagePath != null) {
                    filePath = selectedImagePath;
                } else if (filemanagerstring != null) {
                    filePath = filemanagerstring;
                } else {
                    Toast.makeText(getApplicationContext(), "Unknown path",
                            Toast.LENGTH_LONG).show();
                    Log.e("Bitmap", "Unknown path");
                }

                if (filePath != null) {
                    decodeFile(filePath);
                } else {
                    bitmap = null;
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Internal error",
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }

    }



    class ImageGalleryTask extends AsyncTask<Void, Void, String> {
        @SuppressWarnings("unused")
        @Override        protected String doInBackground(Void... unsued) {
            InputStream is;
            BitmapFactory.Options bfo;
            Bitmap bitmapOrg;
            ByteArrayOutputStream bao ;

            bfo = new BitmapFactory.Options();
            bfo.inSampleSize = 2;
            //bitmapOrg = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + customImage, bfo);
            bao = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
            byte [] ba = bao.toByteArray();
//            String ba1 = Base64.encodeBytes(ba);
            String ba1 = Base64.encodeToString(ba,1);
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("image",ba1));
            nameValuePairs.add(new BasicNameValuePair("cmd","image_android"));
            Log.v("log_tag", System.currentTimeMillis()+".jpg");
            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new                        //  Here you need to put your server file address

                        HttpPost(URL);//"http://www.picsily.com/upload_photo.php");                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                Log.v("log_tag", "In the try Loop" );
            }catch(Exception e){
                Log.v("log_tag", "Error in http connection "+e.toString());
            }
            return "Success";
            // (null);        }

        @Override        protected void onProgressUpdate(Void... unsued) {

        }

        @Override        protected void onPostExecute(String sResponse) {
            try {
                if (dialog.isShowing())
                    dialog.dismiss();
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                        e.getMessage(),
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }

    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL            // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else            return null;
    }

    public void decodeFile(String filePath) {
        // Decode image size        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);

        // The new size we want to scale to        final int REQUIRED_SIZE = 1024;

        // Find the correct scale value. It should be the power of 2.        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // Decode with inSampleSize        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        bitmap = BitmapFactory.decodeFile(filePath, o2);

        imgView.setImageBitmap(bitmap);

    }

}




<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >

    <ImageView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_weight="1"        android:id="@+id/imageView" />


    <Button        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Choose File"        android:id="@+id/btnpilih"        />


    <Button        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Camera"        android:id="@+id/btncamera"        />

    <Button        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Click To Upload File"        android:id="@+id/uploadButton"        />

    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text=""        android:id="@+id/messageText"        android:textColor="#000000"        android:textStyle="bold"        />
</LinearLayout>


<?php
  require_once"konmysqli.php";
    $file_path = "ypathfile/";
   
 $IMG=$_FILES['uploaded_file']['name'];
    $file_path = $file_path . basename( $IMG);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
     
    } else{
        echo "fail";
    }
 ?>

Senin, 03 Februari 2020

Button Add Layer

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/btnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_input_add" />

</android.support.design.widget.CoordinatorLayout>



FloatingActionButton btnAdd=(FloatingActionButton)findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),List_paket.class);
startActivity(i);
finish();
}});


Selasa, 05 November 2019

CONSOLE DEVELOPER GOOGLE COM

https://console.developers.google.com/apis/dashboard?project=trusty-gradient-251202&authuser=0

Configure a Google API Console project


To configure a Google API Console project, click the button below, and specify your app's package name when prompted. You will also need to provide the SHA-1 hash of your signing certificate. See Authenticating Your Client for information.
https://developers.google.com/identity/sign-in/android/start-integrating






Didapat hasil sbb:

{"web":{"client_id":"61032311926-3k27msvu52bpc3irqthh0q8n8eu1745j.apps.googleusercontent.com","project_id":"trusty-gradient-251202","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"neYcHO9lMtpN7qy1udZSzwPW"}}

Sumber2 Android Clarified:
https://androidclarified.com/category/android-examples/


Praktik:
https://androidclarified.com/google-signin-android-example/












Jumat, 20 September 2019

JSON Parsing 0

<?php

$respon = array();
$respon["sukses"] = 0;
$respon["pesan"] = "0 record";
echo json_encode($respon);

?>

<?php
$record = array();
            $record["kode_mahasiswa"] = "Kode 1";
    $record["nama"] = "Nama 1";

            $respon["sukses"] = 1;
            $respon["record"] = array();

            array_push($respon["record"], $record);
            $respon["pesan"] = "$jum record";
    echo json_encode($respon);
?>

++++++++++++++++

package com.example.pelayanananggotakspsi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser() {}

String getIP() {
return "http://192.168.1.11/Siswa/distrokids/";
}

public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
try {
if(method == "POST"){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
else if(method == "GET"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

return jObj;
}
}


+++++++++++++++++++++++++++


package com.example.pelayanananggotakspsi;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Detail_anggota extends Activity {
String ip="";
String kode_anggota;
String kode_anggota0="";
EditText txtkode_anggota;
EditText txtnama_anggota;
EditText txtnik;
EditText txttgl_lahir;
EditText txtjenis_kelamin;
EditText txtdepartemen;
EditText txttelepon;
EditText txtemail;
EditText txtalamat;
EditText txtusername;
EditText txtpassword;
EditText txtgambar;
EditText txtketerangan;
EditText txtstatus;
Button btnProses;
Button btnHapus;

private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();

private static final String TAG_SUKSES = "sukses";
private static final String TAG_record = "record";
private static final String TAG_nama_anggota = "nama_anggota";
private static final String TAG_nik = "nik";
private static final String TAG_tgl_lahir= "tgl_lahir";
private static final String TAG_jenis_kelamin = "jenis_kelamin";
private static final String TAG_departemen = "departemen";
private static final String TAG_alamat = "alamat";
private static final String TAG_username = "username";
private static final String TAG_password = "password";
private static final String TAG_gambar = "gambar";
private static final String TAG_keterangan = "keterangan";
private static final String TAG_status = "status";

@Override  
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_anggota);
ip=jsonParser.getIP();
callMarquee();
txtkode_anggota = (EditText) findViewById(R.id.txtkode_anggota);
txtnama_anggota= (EditText) findViewById(R.id.txtnama_anggota);
txtalamat= (EditText) findViewById(R.id.txtalamat);
txtnik= (EditText) findViewById(R.id.txtnik);
txttgl_lahir= (EditText) findViewById(R.id.txttgl_lahir);
txtjenis_kelamin= (EditText) findViewById(R.id.txtjenis_kelamin);
txtdepartemen= (EditText) findViewById(R.id.txtdepartemen);
txtusername = (EditText) findViewById(R.id.txtusername);
txtpassword= (EditText) findViewById(R.id.txtpassword);
txtgambar= (EditText) findViewById(R.id.txtgambar);
txtketerangan= (EditText) findViewById(R.id.txtketerangan);
txtstatus= (EditText) findViewById(R.id.txtstatus);
btnProses= (Button) findViewById(R.id.btnproses);
btnHapus = (Button) findViewById(R.id.btnhapus);
Intent i = getIntent(); 
kode_anggota0 = i.getStringExtra("pk");
if(kode_anggota0.length()>0){
new get().execute();
btnProses.setText("Update Data");
btnHapus.setVisibility(View.VISIBLE);
}
else{
btnProses.setText("Add New Data");
btnHapus.setVisibility(View.GONE);
}

btnProses.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
kode_anggota= txtkode_anggota.getText().toString();
String lnama_anggota= txtnama_anggota.getText().toString();
String lalamat= txtalamat.getText().toString();
String lnik= txtnik.getText().toString();
String ltgl_lahir= txttgl_lahir.getText().toString();
String ljenis_kelamin= txtjenis_kelamin.getText().toString();
String ldepartemen= txtdepartemen.getText().toString();
String lusername= txtusername.getText().toString();
String lpassword= txtpassword.getText().toString();
String lgambar= txtgambar.getText().toString();
String lketerangan= txtketerangan.getText().toString();
String lstatus= txtstatus.getText().toString();
if(kode_anggota.length()<1){lengkapi("kode_anggota");}
else if(lnama_anggota.length()<1){lengkapi("nama_anggota");}
else if(lalamat.length()<1){lengkapi("alamat");}
else if(lnik.length()<1){lengkapi("nik");}
else if(ltgl_lahir.length()<1){lengkapi("tgl_lahir");}
else if(ljenis_kelamin.length()<1){lengkapi("jenis_kelamin");}
else if(ldepartemen.length()<1){lengkapi("departemen");}
else if(lusername.length()<1){lengkapi("username");}
else if(lpassword.length()<1){lengkapi("password");}
else if(lgambar.length()<1){lengkapi("gambar");}
else if(lketerangan.length()<1){lengkapi("keterangan");}
else if(lstatus.length()<1){lengkapi("status");}
else{
if(kode_anggota0.length()>0){
new update().execute();
}
else{
new save().execute();
}
}//else
}});

btnHapus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
new del().execute();
}});
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class get extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Detail_anggota.this);
pDialog.setMessage("Load data detail. Silahkan tunggu...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
int sukses;
try {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("kode_anggota", kode_anggota0));
String url=ip+"anggota/anggota_detail.php";
Log.v("detail",url);
JSONObject json = jsonParser.makeHttpRequest(url, "GET", params1);
Log.d("detail", json.toString());
sukses = json.getInt(TAG_SUKSES);
if (sukses == 1) {
JSONArray myObj = json.getJSONArray(TAG_record); // JSON Array
final JSONObject myJSON = myObj.getJSONObject(0);
runOnUiThread(new Runnable() {
public void run() {
try {
txtkode_anggota.setText(kode_anggota0);
txtnama_anggota.setText(myJSON.getString(TAG_nama_anggota));
txtgambar.setText(myJSON.getString(TAG_gambar));
txtketerangan.setText(myJSON.getString(TAG_keterangan));
txtalamat.setText(myJSON.getString(TAG_alamat));
txtnik.setText(myJSON.getString(TAG_nik));
txttgl_lahir.setText(myJSON.getString(TAG_tgl_lahir));
txtjenis_kelamin.setText(myJSON.getString(TAG_jenis_kelamin));
txtdepartemen.setText(myJSON.getString(TAG_departemen));
txtusername.setText(myJSON.getString(TAG_username));
txtpassword.setText(myJSON.getString(TAG_password));
txtstatus.setText(myJSON.getString(TAG_status));
} 
catch (JSONException e) {e.printStackTrace();}
}});
}
else{
// jika id tidak ditemukan
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {pDialog.dismiss();}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

class save extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Detail_anggota.this);
pDialog.setMessage("Menyimpan data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
kode_anggota = txtkode_anggota.getText().toString();
String lnama_anggota= txtnama_anggota.getText().toString();
String lnik= txtnik.getText().toString();
String lalamat= txtalamat.getText().toString();
String ltgl_lahir= txttgl_lahir.getText().toString();
String ljenis_kelamin= txtjenis_kelamin.getText().toString();
String ldepartemen= txtdepartemen.getText().toString();
String lgambar= txtgambar.getText().toString();
String lketerangan= txtketerangan.getText().toString();
String lusername= txtusername.getText().toString();
String lpassword= txtpassword.getText().toString();
String lstatus= txtstatus.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("kode_anggota0", kode_anggota0));
params.add(new BasicNameValuePair("kode_anggota", kode_anggota));
params.add(new BasicNameValuePair("nama_anggota", lnama_anggota));
params.add(new BasicNameValuePair("alamat", lalamat));
params.add(new BasicNameValuePair("nik", lnik));
params.add(new BasicNameValuePair("tgl_lahir", ltgl_lahir));
params.add(new BasicNameValuePair("jenis_kelamin", ljenis_kelamin));
params.add(new BasicNameValuePair("departemen", ldepartemen));
params.add(new BasicNameValuePair("gambar", lgambar));
params.add(new BasicNameValuePair("keterangan", lketerangan));
params.add(new BasicNameValuePair("username", lusername));
params.add(new BasicNameValuePair("password", lpassword));
params.add(new BasicNameValuePair("status", lstatus));
String url=ip+"anggota/anggota_add.php";
Log.v("add",url);
JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);
Log.d("add", json.toString());
try {
int sukses = json.getInt(TAG_SUKSES);
if (sukses == 1) {
Intent i = getIntent();
setResult(100, i);
finish();
} else {
// gagal update data
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

protected void onPostExecute(String file_url) {pDialog.dismiss();}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

class update extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Detail_anggota.this);
pDialog.setMessage("Mengubah data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
kode_anggota = txtkode_anggota.getText().toString();
String lnama_anggota= txtnama_anggota.getText().toString();
String lalamat= txtalamat.getText().toString();
String lgambar= txtgambar.getText().toString();
String lnik= txtnik.getText().toString();
String ltgl_lahir= txttgl_lahir.getText().toString();
String ljenis_kelamin= txtjenis_kelamin.getText().toString();
String ldepartemen= txtdepartemen.getText().toString();
String lketerangan= txtketerangan.getText().toString();
String lusername= txtusername.getText().toString();
String lpassword= txtpassword.getText().toString();
String lstatus= txtstatus.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("kode_anggota0", kode_anggota0));
params.add(new BasicNameValuePair("kode_anggota", kode_anggota));
params.add(new BasicNameValuePair("nama_anggota", lnama_anggota));
params.add(new BasicNameValuePair("alamat", lalamat));
params.add(new BasicNameValuePair("nik", lnik));
params.add(new BasicNameValuePair("tgl_lahir", ltgl_lahir));
params.add(new BasicNameValuePair("jenis_kelamin", ljenis_kelamin));
params.add(new BasicNameValuePair("departemen", ldepartemen));
params.add(new BasicNameValuePair("gambar", lgambar));
params.add(new BasicNameValuePair("username", lusername));
params.add(new BasicNameValuePair("status", lstatus));
String url=ip+"anggota/anggota_update.php";
Log.v("update",url);
JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);
Log.d("add", json.toString());
try {
int sukses = json.getInt(TAG_SUKSES);
if (sukses == 1) {
Intent i = getIntent();
setResult(100, i);
finish();
} else {
// gagal update data
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

protected void onPostExecute(String file_url) {pDialog.dismiss();}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class del extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Detail_anggota.this);
pDialog.setMessage("Menghapus data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

protected String doInBackground(String... args) {
int sukses;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("kode_anggota", kode_anggota0));

String url=ip+"anggota/anggota_del.php";
Log.v("delete",url);
JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
Log.d("delete", json.toString());
sukses = json.getInt(TAG_SUKSES);
if (sukses == 1) {
Intent i = getIntent();
setResult(100, i);
finish();
}
} 
catch (JSONException e) {e.printStackTrace();}
return null;  
}

protected void onPostExecute(String file_url) {pDialog.dismiss();}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public void lengkapi(String item){
  new AlertDialog.Builder(this)
  .setTitle("Lengkapi Data")
  .setMessage("Silakan lengkapi data "+item +" !")
  .setNeutralButton("Tutup", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dlg, int sumthin) {
    finish();
   }}).show();
} 
 
 
void callMarquee(){
         Calendar cal = Calendar.getInstance();          
         int jam = cal.get(Calendar.HOUR);
         int menit= cal.get(Calendar.MINUTE);
         int detik= cal.get(Calendar.SECOND);

         int tgl= cal.get(Calendar.DATE);
         int bln= cal.get(Calendar.MONTH);
         int thn= cal.get(Calendar.YEAR);

         String stgl=String.valueOf(tgl)+"-"+String.valueOf(bln)+"-"+String.valueOf(thn);
         String sjam=String.valueOf(jam)+":"+String.valueOf(menit)+":"+String.valueOf(detik);
        
         TextView  txtMarquee=(TextView)findViewById(R.id.txtMarquee);
         txtMarquee.setSelected(true);
         String kata="Selamat Datang @lp2maray.com Aplikasi Android  "+stgl+"/"+sjam+" #";
         String kalimat=String.format("%1$s",TextUtils.htmlEncode(kata));
         txtMarquee.setText(Html.fromHtml(kalimat+kalimat+kalimat)); 
  }
 
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}   
 
}
+++++++++++++++++++