Langsung saja kita ke langkah pembuatannya :
Langkah Pertama, Membuat Database...
CREATE DATABASE db_makanan; CREATE TABLE tbl_makanan ( id INT(4) NOT NULL AUTO_INCREMENT, nama_makanan VARCHAR(32) NOT NULL, harga INT(10) NOT NULL, PRIMARY KEY (id) ) ENGINE=MyISAM;
Setelah itu, kita perlu membuat file php untuk memasukkan data ke dalam database...buat file bernama addmakanan.php
<?php
$nama = $_GET['nama'];
$harga = $_GET['harga'];
$link = mysql_connect('localhost', 'user', 'password') or die('Cannot connect to the DB');
mysql_select_db('db_makanan', $link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "insert into tbl_makanan (nama_makanan,harga) values('".$nama."',".$harga.")";
$result = mysql_query($query, $link) or die('Error query: '.$query);
echo "SUCCESS";
?>
Lalu buat file php dengan nama daftarmakanan.php, untuk menampilkan data..
<?php $link = mysql_connect('localhost', 'user', 'password') or die('Cannot connect to the DB'); mysql_select_db('db_makanan', $link) or die('Cannot select the DB'); /* grab the posts from the db */ $query = "SELECT nama_makanan, harga FROM tbl_makanan"; $result = mysql_query($query, $link) or die('Errorquery: '.$query); $rows = array(); while ($r = mysql_fetch_assoc($result)) { $rows[] = $r; } $data = "{makanan:".json_encode($rows)."}"; echo $data; ?>
Langsung saja, sekarang kita buat pada androidnya..kita buat tambah.xml
<?xml version="1.0" encoding="utf-8"?> <?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"> <TextView android:text="Nama Makanan :" android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView> <EditText android:text="" android:id="@+id/txtNama" android:layout_width="fill_parent" android:layout_height="wrap_content"></EditText> <TextView android:text="Harga :" android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView> <EditText android:text="" android:id="@+id/txtHarga" android:layout_width="fill_parent" android:layout_height="wrap_content"></EditText> <Button android:text="Simpan" android:id="@+id/btnSimpan" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button> </LinearLayout>
Lalu buat daftarmakanan.xml
<?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"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Baca Data Dari server dengan JSON" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Daftar Makanan" /> <TextView android:layout_width="fill_parent" android:id="@+id/TextViewResult" android:layout_height="wrap_content" android:text="Hasil JSON" /> </LinearLayout>
Sekararang Mari kita buat Menu dari aplikasi ini, yang didalamnya terdapat navigasiuntuk masuk ke Form Tambah,
ke Daftar Makanan dan keluar Aplikasi. Edit File MainActivity.java
package com.agus.android.php; /** * Class InsertActivity * @version 1.0 Dec 18, 2011 * @author Agus Haryanto (agus.superwriter@gmail.com) * @website http://agusharyanto.net */ import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends ListActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); // Create an array of Strings, that will be put to our ListActivity String[] menu = new String[] { "Tambah Data", "Tampilkan Data", "Exit" }; // Create an ArrayAdapter, that will actually make the Strings above // appear in the ListView // Menset nilai array ke dalam list adapater sehingga data pada array // akan dimunculkan dalam list this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, menu)); } @Override /**method ini akan mengoveride method onListItemClick * yang ada pada class List Activity * method ini akan dipanggil apabilai ada salah satu item * dari list menu yang dipilih */ protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // Get the item that was clicked Object o = this.getListAdapter().getItem(position); String pilihan = o.toString(); tampilkanPilihan(pilihan); } protected void tampilkanPilihan(String pilihan) { try { Intent i = null; if (pilihan.equals("Tambah Data")) { i = new Intent(this, InsertActivity.class); } else if (pilihan.equals("Tampilkan Data")) { i = new Intent(this, JSONActivity.class); } else if (pilihan.equals("Exit")) { finish(); } else { Toast.makeText(this,"Anda Memilih: " + pilihan + " , " + "Actionnya belum dibuat", Toast.LENGTH_LONG).show(); } startActivity(i); } catch (Exception e) { e.printStackTrace(); } } }
Sekarang Bagian Form Tambah Datanya, Buat Class baru dengan nama InsertActivity.java.
package com.agus.android.php; /** * Class InsertActivity * @version 1.0 Dec 18, 2011 * @author Agus Haryanto (agus.superwriter@gmail.com) * @website http://agusharyanto.net */ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; 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 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 InsertActivity extends Activity { private EditText txtNama; private EditText txtHarga; private Button btnSimpan; // Seusuaikan url dengan nama domain yang anda gunakan private String url = "http://10.0.2.2/android/addmakanan.php"; /** * Method yang dipanggil pada saat aplikaasi dijalankan * */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tambah); txtNama = (EditText) findViewById(R.id.txtNama); txtHarga = (EditText) findViewById(R.id.txtHarga); btnSimpan = (Button) findViewById(R.id.btnSimpan); // daftarkan even onClick pada btnSimpan btnSimpan.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { try { // setiap parameter yang akan dikirim melalui http // harus encode agar // dapat terbaca dengan baik oleh server String nama = URLEncoder.encode(txtNama.getText() .toString(), "utf-8"); String harga = URLEncoder.encode(txtHarga.getText() .toString(), "utf-8"); url += "?nama=" + nama + "&harga=" + harga; getRequest(url); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } /** * Method untuk Mengirimkan data kes erver event by button login diklik * * @param view */ public void getRequest(String Url) { Toast.makeText(this, "Tambah Data " + Url + " ", Toast.LENGTH_SHORT) .show(); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); try { HttpResponse response = client.execute(request); Toast.makeText(this, "Tambah Data " + request(response) + " ", Toast.LENGTH_SHORT).show(); } catch (Exception ex) { Toast.makeText(this, "Tambah Data Gagal !", Toast.LENGTH_SHORT) .show(); } } /** * Method untuk Menenrima data dari server * * @param response * @return */ 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; } }
Waktunya kita buat Class untuk menampilkan data dari server dalam bentuk JSON, buat class baru dengan nama JSONActivity.java
package com.agus.android.php; /** * Class JSONActivity * @version 1.0 Dec 18, 2011 * @author Agus Haryanto (agus.superwriter@gmail.com) * @website http://agusharyanto.net */ 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.JSONObject; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; public class JSONActivity extends Activity { private JSONObject jObject; private String xResult =""; //Seusuaikan url dengan nama domain yang anda gunakan private String url = "http://10.0.2.2/android/daftarmakanan.php"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.daftarmakanan); TextView txtResult = (TextView)findViewById(R.id.TextViewResult); xResult = getRequest(url); try { parse(txtResult); } catch (Exception e) { e.printStackTrace(); } } private void parse(TextView txtResult) throws Exception { jObject = new JSONObject(xResult); JSONArray menuitemArray = jObject.getJSONArray("makanan"); String sret=""; for (int i = 0; i < menuitemArray.length(); i++) { sret +=menuitemArray.getJSONObject(i) .getString("nama_makanan").toString()+" : "; System.out.println(menuitemArray.getJSONObject(i) .getString("nama_makanan").toString()); System.out.println(menuitemArray.getJSONObject(i).getString( "harga").toString()); sret +=menuitemArray.getJSONObject(i).getString( "harga").toString()+"\n"; } txtResult.setText(sret); } /** * Method untuk Mengirimkan data kes erver * event by button login diklik * * @param view */ 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 Menenrima data dari server * @param response * @return */ 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; } }
Lalu Edit AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.agus.android.php" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <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=".InsertActivity" android:label="Tambah Data"> </activity> <activity android:name="JSONActivity" android:label="Daftar Makanan"> </activity> </application> <uses-permission android:name="android.permission.INTERNET"> </uses-permission> </manifest>
Download Tutorial lengkap di http://adf.ly/RJdrZ
Posting Komentar