Rabu, 02 Januari 2013

Aplikasi Android untuk Menambah Data dengan Method POST ke Web Database PHP MySQL

Tulisan ini adalah sambungan dari artikel sebelumnya yaitu Mengambil Data JSON dari PHP MySQL. Silakan download atau ikuti pembuatan program dari Artikel tersebut untuk kemudian kita tambahkan kemampuan Android Menambah Data ke Web PHP MySQL menggunakan Metode POST.

Pada Program utama di MainActivity kita tambahkan beberapa baris program untuk memanggil Activity baru yang berfungsi untuk menambahkan Data yaitu AddActivity :

MainActivity.java

package com.amijaya.androidphpmysqljson;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

// http://cariprogram.blogspot.com
// nuramijaya@gmail.com

public class MainActivity extends Activity {
private JSONObject jObject;
private String jsonResult ="";
private String url = "http://192.168.43.150/json/daftarkota.php";
private String url2 = "http://192.168.43.150/json/delkota.php";
String[] daftarid;
String[] daftarnama;
String[] daftarlatitude;
String[] daftarlongitude;
Menu menu;
public static MainActivity ma;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ma=this;
        RefreshList();
    }
    
    public void RefreshList() {
     try {
         jsonResult = getRequest(url); 
        
         jObject = new JSONObject(jsonResult);
JSONArray menuitemArray = jObject.getJSONArray("kota");

daftarid = new String[menuitemArray.length()];
daftarnama = new String[menuitemArray.length()];
daftarlatitude = new String[menuitemArray.length()];
daftarlongitude = new String[menuitemArray.length()];

for (int i = 0; i < menuitemArray.length(); i++)
{
daftarid[i] = menuitemArray.getJSONObject(i).getString("id").toString();
daftarnama[i] = menuitemArray.getJSONObject(i).getString("nama").toString();
daftarlatitude[i] = menuitemArray.getJSONObject(i).getString("latitude").toString();
daftarlongitude[i] = menuitemArray.getJSONObject(i).getString("longitude").toString();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

ListView ListView01 = (ListView)findViewById(R.id.ListView01);
        ListView01.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, daftarnama));
        
        ListView01.setSelected(true);
        ListView01.setOnItemClickListener(new OnItemClickListener() {
         @Override
         public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
final String selectionid = daftarid[arg2]; 
final String selectionnama = daftarnama[arg2]; 
final String selectionlatitude = daftarlatitude[arg2]; 
final String selectionlongitude = daftarlongitude[arg2]; 
     final CharSequence[] dialogitem = {"Edit", "Delete"};
     AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Pilih ?");
        builder.setItems(dialogitem, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item){
case 0 :
/*Intent i = new Intent(getApplicationContext(), EditActivity.class);  
i.putExtra("id", selectionid);
i.putExtra("nama", selectionnama);
i.putExtra("latitude", selectionlatitude);
i.putExtra("longitude", selectionlongitude);
     startActivity(i);*/

break;
case 1 :
/*getRequest(url2 + "?id=" + selectionid);
RefreshList();
*/
break;
}
}
});
        builder.create().show();
}});

        ((ArrayAdapter)ListView01.getAdapter()).notifyDataSetInvalidated();
        
    }
    
    /**
 * Method untuk Mengirimkan data ke server
 */
public String getRequest(String Url){

String sret="";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(Url);
try{
HttpResponse response = client.execute(request);
sret =request(response);

}catch(Exception ex){
Toast.makeText(this,"Gagal "+sret, Toast.LENGTH_SHORT).show();
}
return sret;

}
/**
 * Method untuk Menerima data dari server
 */
public static String request(HttpResponse response){
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
     this.menu = menu;
    
     menu.add(0, 1, 0, "Tambah").setIcon(android.R.drawable.btn_plus);
     menu.add(0, 2, 0, "Refresh").setIcon(android.R.drawable.ic_menu_rotate);
        menu.add(0, 3, 0, "Exit").setIcon(android.R.drawable.ic_menu_close_clear_cancel);
     return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 1:
         Intent i = new Intent(MainActivity.this, AddActivity.class);
         startActivity(i);
            return true;
        case 2:            
            RefreshList();         
     return true;
        case 3:
            finish();
            return true;
        }
     return false;
    }
}

Kemudian kita buat Activity baru yaitu AddActivity.java :

package com.amijaya.androidphpmysqljson;

import java.util.ArrayList;
import java.util.List;

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;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddActivity extends Activity {
Button btnAddSimpan;
EditText edAddNama;
EditText edAddLatitude;
EditText edAddLongitude;

// http://cariprogram.blogspot.com
// nuramijaya@gmail.com

/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add);
        
        edAddNama = (EditText) findViewById(R.id.edAddNama);
        edAddLatitude = (EditText) findViewById(R.id.edAddLatitude);
        edAddLongitude = (EditText) findViewById(R.id.edAddLongitude);
        
        btnAddSimpan = (Button) findViewById(R.id.btnAddSimpan);
// daftarkan even onClick pada btnSimpan
    btnAddSimpan.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int TIMEOUT_MILLISEC = 10000; 
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); 
nameValuePairs.add(new BasicNameValuePair("nama", edAddNama.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("latitude", edAddLatitude.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("longitude", edAddLongitude.getText().toString()));

   try {
    HttpPost request = new HttpPost("http://192.168.43.150/json/addkota.php");
    request.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = client.execute(request);
}
catch(Exception e){
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Berhasil", Toast.LENGTH_LONG).show();
MainActivity.ma.RefreshList();
finish();
}

});

    }
}

Kemudian tampilannya AddActivity yaitu add.xml kita pakai saja tampilan default kemudian ditambah tiga buah TextView, kemudian tiga buah EditText dengan nama edAddNama, edAddLatitude, edAddLongitude, Kemudian tambahkan satu buah Button dengan Nama btnAddSimpan :

add.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical">
<TextView android:text="Nama" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:id="@+id/edAddNama" android:layout_width="100dp" android:layout_height="wrap_content"></EditText>
<TextView android:text="Latitude" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:id="@+id/edAddLatitude" android:layout_width="100dp" android:layout_height="wrap_content"></EditText>
<TextView android:text="Longitude" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:id="@+id/edAddLongitude" android:layout_width="100dp" android:layout_height="wrap_content"></EditText>
<Button android:text="Simpan" android:id="@+id/btnAddSimpan" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

Android Manifest perlu didaftarkan activity baru yaitu AddActivity  :

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.amijaya.androidphpmysqljson"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
<activity android:name=".AddActivity"
                  android:label="@string/app_name">
        </activity>
        <!--activity android:name=".EditActivity"
                  android:label="@string/app_name">
        </activity-->
    </application>
    <uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>

Hasilnya




Project selengkapnya silakan didownload disini :

https://docs.google.com/open?id=0B4i1FYc_4RXzN2NOb29kYUcycW8

Semoga bermanfaat, Selamat Coding.

Artikel Selanjutnya  Mengedit / update Data ke PHP MySQL menggunakan Method POST