My Education Video Happy watch :)

Rabu, 04 Juli 2012

Contoh simple CRUD android menggunakan php dan mysql

Contoh aplikasi simple CRUD(Mysql) dengan PHP(JSON) dan MYSQL pada Android

Oke, sebelum kita membuat contoh aplikasi sederhana ini, hal-hal yang perlu diketahui oleh pembaca :

- PHP
- MYSQL
- JSON
- Java(Android)

Tentunya kalian semua udah punya eclipse dkk buat develop apps android, oke langsung aja ke contoh programnya
pertama-tama kalian buat dulu kode php-nya di server lokal kalian
disini saya pake WAMP SERVER

oke langkah pertama buat PHP-nya dulu, baru nanti android-nya, tapi terserah kalian sih :p
Simpan difolder htdocs(xampp) atau www yaa(wamp)
Listing koneksi.php

<?php
 $server = "localhost";
 $username = "root";
 $password = "";
 $database = "crud_android";
 mysql_connect($server, $username, $password);
 mysql_select_db($database) or die("Database tidak ada");
?>



nah buat database + tabelnya deh Database : crud_android Tabel : mahasiswa.

create table mahasiswa(
id int(11) not null primary key,
nama varchar(100),
kelas varchar(100),
npm varchar(100)
);


oke lanjut, abis itu siapin tambah_data.php

<?php

require_once __DIR__."koneksi.php";


//Siapin dulu JSON-nya

//$json['status'] <- menandakan status insert data, jika 1 maka berhasil, jika 0 maka terjadi kesalahan

//$json['pesan'] <- menandakan pesan apabila dilakukan insert data sukses atau tidak

$json = array();

if(isset($_POST['nama'])&&isset($_POST['kelas'])&&isset($_POST['npm'])){
//insert query
$nama = $_POST['nama'];
$kelas = $_POST['kelas'];
$npm = $_POST['npm'];

$sqlinsert = "insert into mahasiswa(nama, kelas, npm) values ('$nama','$kelas','$npm')";
$hasil = mysql_query($sqlinsert);

if($hasil){
//Kalo query sukses
$json['status'] = 1;
$json['pesan'] = "Data sudah dimasukkan kedalam database";
echo json_encode($json);
}else{
$json['status'] = 0;
$json['pesan'] = "Kesalahan query";
echo json_encode($json);   
}

}else{
$json['status'] = 0;
$json['pesan'] = "Lengkapi data anda";
echo json_encode($json);
}

Sesudah itu, kita buat project androidnya :)
klo saya pake lib Android 2.2
File -> New -> Project
Android 2.2

Di activity main kita buat 1 tombol, tombol Tambah data
Main.java

Button tambah = (Button)findViewById(R.id.bTambahData);
tambah.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent i = new Intent(Main.this, TambahData.class);
finish();
startActivity(i);
}
});

Di activity TambahData.java ada 3 widget edit text buat ngisi data ke database
Nama, Kelas, NPM

pas di klik ok, akan melakukan insert data ke database mysql

isi listing kode TambahData.java

package com.list.crud;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class TambahData extends Activity{
 
 Button kirim;
 EditText nama, kelas, npm;
 ProgressDialog progress;
 JSONParser jsonParser;
 
 String url = "http://10.0.2.2/CRUD/tambah_data.php";
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.tambahdata);
  kirim = (Button) findViewById(R.id.bKirim);
  nama = (EditText) findViewById(R.id.etNama);
  kelas = (EditText) findViewById(R.id.etKelas);
  npm = (EditText) findViewById(R.id.etNpm);
  jsonParser = new JSONParser();
  
  kirim.setOnClickListener(new View.OnClickListener() {
   
   public void onClick(View arg0) {
    new Tambah().execute();
   }
  });
 }
 
 class Tambah extends AsyncTask<String, String, String>{

  @Override
  protected void onPreExecute() {
   // TODO Auto-generated method stub
   super.onPreExecute();
   progress = new ProgressDialog(TambahData.this);
   progress.setMax(100);
   progress.setIndeterminate(false);
   progress.show();
  }

  @Override
  protected String doInBackground(String... arg0) {
   String nm = nama.getText().toString();
   String kls = kelas.getText().toString();
   String nomor = npm.getText().toString();
   
   List<NameValuePair> value = new ArrayList<NameValuePair>();
   value.add(new BasicNameValuePair("nama", nm));
   value.add(new BasicNameValuePair("kelas", kls));
   value.add(new BasicNameValuePair("npm", nomor));
   
   JSONObject js = null;
   try {
    js = jsonParser.getObject(url,"POST",value);
   } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }
   
   try {
    int status = js.getInt("status");
     if(status == 1){
      Log.i("Sukses", "Produk telah ditambah");
     }else{
      Log.d("Error", "Gagal menambah produk");
     }
   } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
   return null;
  }
  
  @Override
  protected void onPostExecute(String result) {
   // TODO Auto-generated method stub
   super.onPostExecute(result);
   progress.dismiss();
  }
 }
}

Ini listing kode JSONParser.java

package com.list.crud;

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;

public class JSONParser {

	InputStream is;
	String json;
	
	public JSONObject getObject(String url, String method, List<NameValuePair> value) throws IOException {
		
		if(method == "POST"){
			DefaultHttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(url);
			try {
				post.setEntity(new UrlEncodedFormEntity(value));
				HttpResponse response = client.execute(post);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}else if(method == "GET"){
			DefaultHttpClient client = new DefaultHttpClient();
			String param = URLEncodedUtils.format(value, "utf-8");
			url += "?" + param;
			HttpGet get = new HttpGet(url);
			HttpResponse response;
			try {
				response = client.execute(get);
				is = response.getEntity().getContent();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
		StringBuilder sb = new StringBuilder();
		String line;
		while((line = reader.readLine())!=null){
			sb.append(line+"\n");
		}
		is.close();
		json = sb.toString();
		JSONObject object = null;
		try {
			object = new JSONObject(json);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return object;
	}

}



Nah, beres deh, penjelasan listing programnya, pada intinya ketika semua form udah diisi, terus klik tambah maka yang terjadi akan menjalankan kelas yang meng-extend AsyncTask, jika status respon yang dikembalikan adalah 1(Sukses menginsert data baru) maka data baru akan ditambah :)

untuk lebih jelasnya, download aja nih datanya, langsung diimport ke eclipsenya ya :)

Download

5 komentar:

Anda bebas berkomentar sesuai dengan topik yang telah disampaikan, anda bisa bertanya apabila mengalami kesulitan. atau bisa langsung email billyfebram@yahoo.co.id