Koneksi Android, PHP, MySQL Offline Menggunakan Xampp For Windows 2 ( Cloud Computing )
Posted on 08 July, 2013 by Unknown
Bismillahirrahmanirrahim
Assalamualaikum Wr. Wb.
Nerusin Postingan yang tertunda karena perut keroncongan beberapa saat yang lalu he...he...artikelnya tentang Koneksi Android, PHP, MySQL Offline Menggunakan Xampp For Windows 2 ( Cloud Computing ) jadi pake angka 2, kita lanjutkan sob...untuk tahap selanjutnya pembuatan program Androidnya.
- isibiodata.xml
- daftarbiodataonline.xml
- daftarbiodataoffline.xml
- OperasiDatabase.java
- OperasiInternet.java
- MenuActivity.java
- IsiBiodata.java
- DaftarBiodataOnline.java
- DaftarBiodataOffline.java
- AndroidManifest.xml
1. isibiodata.xml
2. daftarbiodataonline.xml
3. daftarbiodataoffline.xml
4. OperasiDatabase.java
package dedendeni75.blogspot.com.cloudstorage; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class OperasiDatabase extends SQLiteOpenHelper{ private static final String NAMA_DATABASE = "dbMahasiswa"; private static final String NAMA_TABLE = "biodata"; public OperasiDatabase(Context context) { super(context, NAMA_DATABASE, null, 1); } @Override public void onCreate(SQLiteDatabase arg0) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } //method createTable untuk membuat table biodata public void createTable(SQLiteDatabase db){ db.execSQL("CREATE TABLE if not exists "+NAMA_TABLE+" (nim VARCHAR(20) PRIMARY KEY, " + "nama varchar(50), alamat TEXT);"); } public Cursor selectBiodata(SQLiteDatabase db, String sql){ Cursor cursor = db.rawQuery(sql,null); return cursor; } //method insertBiodata untuk mengisikan data ke biodata. public void modifyBiodata(SQLiteDatabase db, String[] data){ String whereClause = "nim=?"; String[] whereArgs = new String[] {String.valueOf(data[0])}; db.delete(NAMA_TABLE, whereClause, whereArgs); ContentValues cv=new ContentValues(); cv.put("nim", data[0]); cv.put("nama", data[1]); cv.put("alamat", data[2]); db.insert(NAMA_TABLE,null,cv); } //method deleteBiodata untuk mengisikan data ke biodata. public void deleteBiodata(SQLiteDatabase db, String nim){ String whereClause = "nim=?"; String[] whereArgs = new String[] {String.valueOf(nim)}; db.delete(NAMA_TABLE, whereClause, whereArgs); } }
5. OperasiInternet.java
package dedendeni75.blogspot.com.cloudstorage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ProgressDialog; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; public class OperasiInternet extends AsyncTask{ //IP address 10.0.2.2 adalah IP local pada PC anda. //Jika server berada di lain PC, maka sesuaikan IP Address server anda private String URL ="http://10.0.2.2"; private ProgressDialog pDialog; private Context mContext; private String responsefromserver; private JSONObject jsonfromserver = null; private JSONObject jsonfromclient = null; private boolean postformatjson = false; //constructor public OperasiInternet(Context c){ mContext = c; } //buat event handler untuk menandai proses postExecute telah selesai public interface OnPostExecuteListener { public abstract void OnPostExecute(); } private OnPostExecuteListener onPostExecuteListener = null; public void SetOnPostExecuteListener(OnPostExecuteListener l) { onPostExecuteListener = l; } public boolean CheckInternetConnection() { //status koneksi internet dari connectivity manager ConnectivityManager connectivityManager = (ConnectivityManager) mContext .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager != null) { NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo(); if (networkInfo != null) { for (int i = 0; i < networkInfo.length; i++) { if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; } @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(mContext); pDialog.setMessage("Mohon sabar menunggu, sedang proses koneksi ke internet"); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... params) { responsefromserver = SendToServer(URL+"/coba/biodatajson.php"); return null; } protected void onPostExecute(String file_url) { pDialog.dismiss(); //raise event onPostExecuteListener.OnPostExecute(); } public String SendToServer(String url) { //set timeout HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 50000); HttpConnectionParams.setSoTimeout(params, 50000); // Eksekusi post ke server HttpClient httpclient = new DefaultHttpClient(params); HttpPost httppost = new HttpPost(url); //httppost.set String text=""; try { //baca parameter JSON jika data yg dikirim ke server dalam bentuk JSON if(postformatjson){ // JSON data: JSONArray postjson=new JSONArray(); postjson.put(jsonfromclient); // post data json httppost.setHeader("json",jsonfromclient.toString()); httppost.getParams().setParameter("jsonpost",postjson); } HttpResponse response = httpclient.execute(httppost); // baca response dari server if(response != null) { InputStream is = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n");// backslash \ } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } text = sb.toString(); } }catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } return text; } public void SetJSON(JSONObject json){ postformatjson = true; jsonfromclient = json; } public JSONObject GetJSON(){ try { jsonfromserver = new JSONObject(responsefromserver); } catch (JSONException e) { //Log.e("JSON Parser", "Error parsing data " + e.toString()); } return jsonfromserver; } public String GetText() throws InterruptedException{ return responsefromserver; } }//end class
6. MenuActivity.java
package dedendeni75.blogspot.com.cloudstorage; 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 MenuActivity extends ListActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String menu[] = new String[]{"Isi Biodata", "Daftar Biodata Online", "Daftar Biodata Offline", "Exit"}; this.setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,menu)); OperasiInternet oi = new OperasiInternet(this); if(oi.CheckInternetConnection()) Toast.makeText(this, "Koneksi Internet OK", 500).show(); else Toast.makeText(this, "Koneksi internet tidak tersedia\n" + "Silahkan aktifkan koneksi internet anda", 500).show(); } @Override protected void onListItemClick(ListView l, View v, int position, long id){ super.onListItemClick(l, v, position, id); Object obj = this.getListAdapter().getItem(position); String pilihan = obj.toString(); Intent myIntent = null; if(pilihan.equalsIgnoreCase("exit")) finish(); else { if(pilihan.equalsIgnoreCase("isi biodata")){ myIntent = new Intent(this, IsiBiodata.class); myIntent.putExtra("status", "baru"); } else if(pilihan.equalsIgnoreCase("daftar biodata online")) myIntent = new Intent(this, DaftarBiodataOnline.class); else if(pilihan.equalsIgnoreCase("daftar biodata offline")) myIntent = new Intent(this, DaftarBiodataOffline.class); startActivity(myIntent); } } }
7. IsiBiodata.java
package dedendeni75.blogspot.com.cloudstorage; import org.json.JSONException; import org.json.JSONObject; import dedendeni75.blogspot.com.cloudstorage.R; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class IsiBiodata extends Activity{ private OperasiDatabase oprDatabase = null; private SQLiteDatabase db = null; private String[] data = null; private EditText txtnim; private EditText txtnama; private EditText txtalamat; private Button btnsimpan; private static OperasiInternet oi; @Override public void onCreate(Bundle savedInstanceState) { String nim =""; String nama =""; String alamat =""; super.onCreate(savedInstanceState); setContentView(R.layout.isibiodata); oprDatabase = new OperasiDatabase(this); db = oprDatabase.getWritableDatabase(); oprDatabase.createTable(db); Intent sender = getIntent(); nim = sender.getExtras().getString("nim"); nama = sender.getExtras().getString("nama"); alamat = sender.getExtras().getString("alamat"); txtnim = (EditText) findViewById(R.id.txtnim); txtnim.setText(nim); txtnama = (EditText) findViewById(R.id.txtnama); txtnama.setText(nama); txtalamat = (EditText) findViewById(R.id.txtalamat); txtalamat.setText(alamat); btnsimpan = (Button) findViewById(R.id.btnsimpan); btnsimpan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { simpandata(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } private void simpandata() throws InterruptedException{ data = new String[]{ txtnim.getText().toString(), txtnama.getText().toString(), txtalamat.getText().toString() }; JSONObject json = new JSONObject(); try { json.put("nim", txtnim.getText().toString() ); json.put("nama", txtnama.getText().toString()); json.put("alamat", txtalamat.getText().toString()); json.put("status", "modifikasi"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } oi = new OperasiInternet(this); if(oi.CheckInternetConnection()){ oi.SetJSON(json); oi.execute(); oi.SetOnPostExecuteListener( new OperasiInternet.OnPostExecuteListener() { @Override public void OnPostExecute() { try { String responsedariserver = oi.GetText(); if(responsedariserver.isEmpty()){ oprDatabase.modifyBiodata(db, data); messageDialog("Tidak ada response dari server\n" + "Untuk sementara data disimpan pada memory HP anda"); clearText(); } else { messageDialog(responsedariserver); oprDatabase.deleteBiodata(db, txtnim.getText().toString()); clearText(); } } catch (InterruptedException e) { e.printStackTrace(); } } } ); } else { oprDatabase.modifyBiodata(db, data); messageDialog("Gagal melakukan Koneksi internet \n" + "Untuk sementara data disimpan pada memory HP anda"); clearText(); } } public void onDestroy() { super.onDestroy(); db.close(); } private void messageDialog(String message){ AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("Alert Dialog"); alertDialog.setMessage(message); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); alertDialog.show(); } private void clearText(){ txtnim.setText(""); txtnama.setText(""); txtalamat.setText(""); } }
8. DaftarBiodataOnline.java
package dedendeni75.blogspot.com.cloudstorage; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import dedendeni75.blogspot.com.cloudstorage.R; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; public class DaftarBiodataOnline extends Activity{ private OperasiInternet oi; private Button btnhapus; private Button btnedit; private Button btnrefresh; private String datadipilih=""; private JSONObject json = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.daftarbiodataonline); try { GetData(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } final AlertDialog.Builder dialog = new AlertDialog.Builder(this); btnedit = (Button) findViewById(R.id.btnedit); btnedit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!datadipilih.isEmpty()){ TampilkanEditBiodata(); } } }); btnhapus = (Button) findViewById(R.id.btnhapus); btnhapus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!datadipilih.isEmpty()){ dialog.setTitle("Konfirmasi"); dialog.setMessage("Anda yakin akan menghapus data "+datadipilih+" ini ?"); dialog.setNegativeButton("Cancel", null); dialog.setPositiveButton("Ok", new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { try { hapusdata(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //nim = "";nama="";alamat=""; } }); dialog.show(); } } }); btnrefresh = (Button) findViewById(R.id.btnrefresh); btnrefresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { GetData(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } private JSONObject GetData() throws InterruptedException{ JSONObject jsontoserver = new JSONObject(); try { jsontoserver.put("status", "ambildata"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } oi = new OperasiInternet(this); if(oi.CheckInternetConnection()){ oi.SetJSON(jsontoserver); oi.execute(); oi.SetOnPostExecuteListener( new OperasiInternet.OnPostExecuteListener() { @Override public void OnPostExecute() { try { if(!oi.GetText().isEmpty()){ json = oi.GetJSON(); TampilkanData(json); } else messageDialog("Tidak ada respon dari server!"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ); } return json; } private void TampilkanData(JSONObject json){ try { JSONArray jsonarr = json.getJSONArray("tables"); TableLayout TL=(TableLayout) findViewById(R.id.tableLayout); TL.removeAllViews(); int jml_baris = jsonarr.length(); String[][] data=new String[jml_baris][3]; for(int i = 0; i< jml_baris;i++){ JSONObject jobj = jsonarr.getJSONObject(i); data[i][0] = jobj.getString("nim"); data[i][1] = jobj.getString("nama"); data[i][2] = jobj.getString("alamat"); } TableLayout.LayoutParams ParameterTableLayout=new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT); for(int awal=0; awal
9. DaftarBiodataOffline.java
package dedendeni75.blogspot.com.cloudstorage; import org.json.JSONException; import org.json.JSONObject; import dedendeni75.blogspot.com.cloudstorage.R; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; public class DaftarBiodataOffline extends Activity{ private OperasiInternet oi; private OperasiDatabase oprDatabase = null; private SQLiteDatabase db = null; private Cursor dbCursor = null; private Button btnupload; private Button btnedit; private Button btnrefresh; private String datadipilih=""; private String nim=""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.daftarbiodataoffline); oprDatabase = new OperasiDatabase(this); db = oprDatabase.getWritableDatabase(); oprDatabase.createTable(db); TampilkanData(); btnrefresh = (Button) findViewById(R.id.btnrefresh); btnrefresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TampilkanData(); } }); btnedit = (Button) findViewById(R.id.btnedit); btnedit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!datadipilih.isEmpty()){ TampilkanEditBiodata(); } } }); btnupload = (Button) findViewById(R.id.btnupload); btnupload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { if(!datadipilih.isEmpty()){ uploaddata(); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } private void TampilkanData(){ TableLayout TL=(TableLayout) findViewById(R.id.tableLayout); TL.removeAllViews(); dbCursor = oprDatabase.selectBiodata(db, "SELECT * FROM biodata"); dbCursor.moveToFirst(); int jml_baris=dbCursor.getCount(); if(jml_baris == 0) return; int kol_nim=dbCursor.getColumnIndex("nim"); int kol_nama=dbCursor.getColumnIndex("nama"); int kol_alamat=dbCursor.getColumnIndex("alamat"); int indeks=1; String[][] data=new String[jml_baris][3]; data[0][0]=dbCursor.getString(kol_nim); data[0][1]=dbCursor.getString(kol_nama); data[0][2]=dbCursor.getString(kol_alamat); if(dbCursor!=null){ while(dbCursor.moveToNext()){ data[indeks][0]=dbCursor.getString(kol_nim); data[indeks][1]=dbCursor.getString(kol_nama); data[indeks][2]=dbCursor.getString(kol_alamat); indeks++; } } TableLayout.LayoutParams ParameterTableLayout=new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT); for(int awal=0; awal
10. AndroidManifest.xml
Setelah selesai semua pembuatan program androidnya dengan script code diatas, atau sobat ingin mencobanya langsung silahkan donwnload contoh programnya AplikasiCloudComputing sekarang saatnya kita coba program androidnya. Seperti biasa jalankan AVD (Android Virtual Manager) nya, lalu masuk pada program android yang telah kita buat AplikasiCloudStorage dan coba input data melalui program AplikasiCloudStorage
Setelah data kita input melalui program AplikasiCloudStorage, hasilnya dapat kita lihat pada database server. lihat screenshotnya dibawah ini
Untuk edit, hapus, dan jika sobat ingin mencoba langsung koneksi ke server hosting silahkan sobat lihat pada postingan ane sebelumnya mengenai Koneksi Android Dengan PHP, Mysql dan Web Hosting.
Demikian postingan ane kali ini semoga bermanfaat
Wassalamualaikum Wr. Wb.
Description:Koneksi Android, PHP, MySQL Offline Menggunakan Xampp For Windows 2 ( Cloud Computing )
Rating: 5
Reviewer: Unknown
ItemReviewed: Koneksi Android, PHP, MySQL Offline Menggunakan Xampp For Windows 2 ( Cloud Computing )
Labels Android
4 Responses to “dedendeni75blog ”
Popular Posts
-
Download Driverpack 13 FINAL 2013 DriverPack 13 adalah merupakan sebuah program yang berisi kumpulan-kumpulan driver untuk VGA, Chipset, S...
-
Bismillahirrahmanirrahim Assalamualaikum Wr. Wb. Nerusin Postingan yang tertunda karena perut keroncongan beberapa saat yang lalu he....
gw coba kok ga bisa ya..
waktu input data dan mo di simpen di phpmyadmin nya ada eror gt.. koneksi IP uda bener..
how?
error nya gimana sob? untuk localhost URL-nya bisa diganti dengan yang ini http://10.0.2.2
terimakasih om udah mau share...
beginilah indahnya berbagi :)
sama-sama sob...terimakasih kunjungannya ya...