TUTORIAL MEMBUAT APLIKASI CRUD (CREATE, READ, UPDATE, DELETE) SEDERHANA DI ANDROID DENGAN DATABASE DI SERVER (PART 2)
Sebelumnya baca TUTORIAL MEMBUAT APLIKASI CRUD (CREATE, READ, UPDATE, DELETE) SEDERHANA DI ANDROID DENGAN DATABASE DI SERVER (PART 1)
Sekarang kita lanjut untuk membuat kelas yang digunakan untuk mengupdate dan men-delete data mahasiswa. Idenya adalah ketika sebuah item mahasiswa dari list mahasiswa di-klik maka akan menuju activity untuk update/delete.
Kita buat dulu activity_updatedelete.xml, berikut isinya :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:padding="10dp"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/id_mhs"
android:visibility="gone"/> <!--untuk membuat textview tidak tampil-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Nama"
android:id="@+id/textView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextNama" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="NIM"
android:id="@+id/textView2"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextNim"
android:layout_gravity="center_horizontal" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight="1"
>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Update"
android:layout_weight="0.5"
android:id="@+id/buttonUpdate"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Delete"
android:layout_weight="0.5"
android:id="@+id/buttonDelete" />
</LinearLayout>
</LinearLayout>
Selanjutnya, kita buat kelas boundary-nya yaitu UpdateDeleteActivity.java, kelas ini dibuat extends ActionBarActivity, dan jangan lupa kita definisikan juga setiap TextView, Button, maupun EditText-nya. Berikut kodingnya :
package com.vhiefa.simplecrud; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * Created by Afifatul on 6/18/2015. */ public class UpdateDeleteActivity extends ActionBarActivity { EditText EditTxtnama, EditTxtnim; TextView TxtViewId; Button UpdateBtn, DeleteBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_updatedelete); EditTxtnama = (EditText) findViewById(R.id.editTextNama); EditTxtnim = (EditText) findViewById(R.id.editTextNim); TxtViewId = (TextView) findViewById(R.id.id_mhs); UpdateBtn = (Button) findViewById(R.id.buttonUpdate); DeleteBtn = (Button) findViewById(R.id.buttonDelete); } }
Kita update AndroidManifest.xml agar kelas UpdateDeleteActivity bisa dipanggil di aplikasi android kita, tambahkan code berikut :
<activity
android:name="com.vhiefa.simplecrud.UpdateDeleteActivity"
android:label="Detail Mahasiswa"
android:parentActivityName="com.vhiefa.simplecrud.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.vhiefa.simplecrud.MainActivity" />
</activity>
Sehingga koding di AndroidManifest.xml secara keseluruhan menjadi sebagai berikut :
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.vhiefa.simplecrud" > <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <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="com.vhiefa.simplecrud.UpdateDeleteActivity" android:label="Detail Mahasiswa" android:parentActivityName="com.vhiefa.simplecrud.MainActivity" > <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.vhiefa.simplecrud.MainActivity" /> </activity> </application> </manifest>
Langkah 10
Kita update lagi koding di MainActivity.java, karena kita akan membuat agar list item mahasiswa ketika di-klik bisa menuju activity update/delete. Kita juga akan membuat id,nama, dan nim mahasiswa ter-parsing ke kelas UpdateDeleteActivity. Tambahkan koding berikut di dalam method onCreate :
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int urutan, long id) {
//dapatkan data id, nama, nim mahasiswa dan simpan dalam variable string
String idmhs = ((TextView) view.findViewById(R.id.id_mhs)).getText().toString();
String nama = ((TextView) view.findViewById(R.id.nama_mhs)).getText().toString();
String nim = ((TextView) view.findViewById(R.id.nim_mhs)).getText().toString();
//varible string tadi kita simpan dalam suatu Bundle, dan kita parse bundle tersebut bersama intent menuju kelas UpdateDeleteActivity
Intent i = null;
i = new Intent(MainActivity.this, UpdateDeleteActivity.class);
Bundle b = new Bundle();
b.putString("id_mhs", idmhs);
b.putString("nama_mhs", nama);
b.putString("nim_mhs", nim);
i.putExtras(b);
startActivity(i);
}
});
Sehingga seluruh koding di MainActivity.java menjadi :
package com.vhiefa.simplecrud; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class MainActivity extends ActionBarActivity { ListView list; JSONParser jParser = new JSONParser(); ArrayList<Mahasiswa> daftar_mhs = new ArrayList<Mahasiswa>(); JSONArray daftarMhs = null; String url_read_mhs = "http://api.vhiefa.net76.net/simple_crud/read_mhs.php"; // JSON Node names, ini harus sesuai yang di API public static final String TAG_SUCCESS = "success"; public static final String TAG_MHS = "mahasiswa"; public static final String TAG_ID_MHS = "id_mhs"; public static final String TAG_NAMA_MHS = "nama"; public static final String TAG_NIM_MHS = "nim"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); list = (ListView) findViewById(R.id.listview_mhs); //jalankan ReadMhsTask ReadMhsTask m= (ReadMhsTask) new ReadMhsTask().execute(); list.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int urutan, long id) { //dapatkan data id, nama, nim mahasiswa dan simpan dalam variable string String idmhs = ((TextView) view.findViewById(R.id.id_mhs)).getText().toString(); String nama = ((TextView) view.findViewById(R.id.nama_mhs)).getText().toString(); String nim = ((TextView) view.findViewById(R.id.nim_mhs)).getText().toString(); //varible string tadi kita simpan dalam suatu Bundle, dan kita parse bundle tersebut bersama intent menuju kelas UpdateDeleteActivity Intent i = null; i = new Intent(MainActivity.this, UpdateDeleteActivity.class); Bundle b = new Bundle(); b.putString("id_mhs", idmhs); b.putString("nama_mhs", nama); b.putString("nim_mhs", nim); i.putExtras(b); startActivity(i); } }); } class ReadMhsTask extends AsyncTask<String, Void, String> { ProgressDialog pDialog; @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Mohon Tunggu.."); pDialog.setIndeterminate(true); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... sText) { String returnResult = getMhsList(); //memanggil method getMhsList() return returnResult; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); pDialog.dismiss(); if(result.equalsIgnoreCase("Exception Caught")) { Toast.makeText(MainActivity.this, "Unable to connect to server,please check your internet connection!", Toast.LENGTH_LONG).show(); } if(result.equalsIgnoreCase("no results")) { Toast.makeText(MainActivity.this, "Data empty", Toast.LENGTH_LONG).show(); } else { list.setAdapter(new MahasiswaAdapter(MainActivity.this,daftar_mhs)); //Adapter menampilkan data mahasiswa ke dalam listView } } //method untuk memperoleh daftar mahasiswa dari JSON public String getMhsList() { Mahasiswa tempMhs = new Mahasiswa(); List<NameValuePair> parameter = new ArrayList<NameValuePair>(); try { JSONObject json = jParser.makeHttpRequest(url_read_mhs,"POST", parameter); int success = json.getInt(TAG_SUCCESS); if (success == 1) { //Ada record Data (SUCCESS = 1) //Getting Array of daftar_mhs daftarMhs = json.getJSONArray(TAG_MHS); // looping through All daftar_mhs for (int i = 0; i < daftarMhs.length() ; i++){ JSONObject c = daftarMhs.getJSONObject(i); tempMhs = new Mahasiswa(); tempMhs.setMhsId(c.getString(TAG_ID_MHS)); tempMhs.setMhsName(c.getString(TAG_NAMA_MHS)); tempMhs.setMhsNIM(c.getString(TAG_NIM_MHS)); daftar_mhs.add(tempMhs); } return "OK"; } else { //Tidak Ada Record Data (SUCCESS = 0) return "no results"; } } catch (Exception e) { e.printStackTrace(); return "Exception Caught"; } } } }
Langkah 11
Selanjutnya kita buka lagi UpdateDeleteActivity.java dan kita masukan kode yang menangkap bundle yang telah di-parsing dari kelas MainActivity tadi. Masukan code berikut :
//menangkap bundle yang telah di-parsed dari MainActivity
Bundle b = getIntent().getExtras();
String isi_id_mhs = b.getString("id_mhs");
String isi_nama_mhs= b.getString("nama_mhs");
String isi_nim_mhs= b.getString("nim_mhs");
//meng-set bundle tersebut
EditTxtnama.setText(isi_nama_mhs);
EditTxtnim.setText(isi_nim_mhs);
TxtViewId.setText(isi_id_mhs);
Langkah 12
Kita buat AsyncTask di UpdateDeleteActivity untuk update data mahasiswa, kita beri nama UpdateMhsTask. Berikut kodingnya :
class UpdateMhsTask extends AsyncTask<String, Void, String>
{
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UpdateDeleteActivity.this);
pDialog.setMessage("Mohon Tunggu..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... sText) {
List<NameValuePair> parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair(TAG_ID_MHS, idStr));
parameter.add(new BasicNameValuePair(TAG_NAMA_MHS, namaStr));
parameter.add(new BasicNameValuePair(TAG_NIM_MHS, nimStr));
try {
JSONObject json = jParser.makeHttpRequest(url_update_mhs,"POST", parameter);
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
return "OK";
}
else {
return "FAIL";
}
} catch (Exception e) {
e.printStackTrace();
return "Exception Caught";
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
if(result.equalsIgnoreCase("Exception Caught"))
{
Toast.makeText(UpdateDeleteActivity.this, "Unable to connect to server,please check your internet connection!", Toast.LENGTH_LONG).show();
}
if(result.equalsIgnoreCase("FAIL"))
{
Toast.makeText(UpdateDeleteActivity.this, "Fail.. Try Again", Toast.LENGTH_LONG).show();
}
else {
Intent i = null;
i = new Intent(UpdateDeleteActivity.this, MainActivity.class);
startActivity(i);
}
}
}
Langkah 13
Kita buat AsyncTask di UpdateDeleteActivity untuk delete data mahasiswa, kita beri nama DeleteMhsTask. Berikut kodingnya :
class DeleteMhsTask extends AsyncTask<String, Void, String>
{
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UpdateDeleteActivity.this);
pDialog.setMessage("Mohon Tunggu..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... sText) {
List<NameValuePair> parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair(TAG_ID_MHS, idStr));
try {
JSONObject json = jParser.makeHttpRequest(url_delete_mhs,"POST", parameter);
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
return "OK";
}
else {
return "FAIL";
}
} catch (Exception e) {
e.printStackTrace();
return "Exception Caught";
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
if(result.equalsIgnoreCase("Exception Caught"))
{
Toast.makeText(UpdateDeleteActivity.this, "Unable to connect to server,please check your internet connection!", Toast.LENGTH_LONG).show();
}
if(result.equalsIgnoreCase("FAIL"))
{
Toast.makeText(UpdateDeleteActivity.this, "Fail.. Try Again", Toast.LENGTH_LONG).show();
}
else {
Intent i = null;
i = new Intent(UpdateDeleteActivity.this, MainActivity.class);
startActivity(i);
}
}
}
Langkah 14
Kita buat agar button update dan button delete pada UpdateDeleteActivity bisa berfungsi sebagaimana mestinya. Tambahkan koding berikut :
UpdateBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
idStr = TxtViewId.getText().toString();
namaStr = EditTxtnama.getText().toString();
nimStr = EditTxtnim.getText().toString();
new UpdateMhsTask().execute();
}
});
DeleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
idStr = TxtViewId.getText().toString();
new DeleteMhsTask().execute();
}
});
Sehingga secara keseluruhan isi UpdateDeleteActivity.java adalah sebagai berikut :
package com.vhiefa.simplecrud; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by Afifatul on 6/18/2015. */ public class UpdateDeleteActivity extends ActionBarActivity { JSONParser jParser = new JSONParser(); String url_update_mhs= "http://api.vhiefa.net76.net/simple_crud/update_mhs.php"; String url_delete_mhs= "http://api.vhiefa.net76.net/simple_crud/delete_mhs.php"; // JSON Node names, ini harus sesuai yang di API public static final String TAG_SUCCESS = "success"; public static final String TAG_ID_MHS = "id_mhs"; public static final String TAG_NAMA_MHS = "nama"; public static final String TAG_NIM_MHS = "nim"; EditText EditTxtnama, EditTxtnim; TextView TxtViewId; Button UpdateBtn, DeleteBtn; String namaStr, nimStr, idStr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_updatedelete); EditTxtnama = (EditText) findViewById(R.id.editTextNama); EditTxtnim = (EditText) findViewById(R.id.editTextNim); TxtViewId = (TextView) findViewById(R.id.id_mhs); UpdateBtn = (Button) findViewById(R.id.buttonUpdate); DeleteBtn = (Button) findViewById(R.id.buttonDelete); //menangkap bundle yang telah di-parsed dari MainActivity Bundle b = getIntent().getExtras(); String isi_id_mhs = b.getString("id_mhs"); String isi_nama_mhs= b.getString("nama_mhs"); String isi_nim_mhs= b.getString("nim_mhs"); //meng-set bundle tersebut EditTxtnama.setText(isi_nama_mhs); EditTxtnim.setText(isi_nim_mhs); TxtViewId.setText(isi_id_mhs); UpdateBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { idStr = TxtViewId.getText().toString(); namaStr = EditTxtnama.getText().toString(); nimStr = EditTxtnim.getText().toString(); new UpdateMhsTask().execute(); } }); DeleteBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { idStr = TxtViewId.getText().toString(); new DeleteMhsTask().execute(); } }); } class UpdateMhsTask extends AsyncTask<String, Void, String> { ProgressDialog pDialog; @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(UpdateDeleteActivity.this); pDialog.setMessage("Mohon Tunggu.."); pDialog.setIndeterminate(true); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... sText) { List<NameValuePair> parameter = new ArrayList<NameValuePair>(); parameter.add(new BasicNameValuePair(TAG_ID_MHS, idStr)); parameter.add(new BasicNameValuePair(TAG_NAMA_MHS, namaStr)); parameter.add(new BasicNameValuePair(TAG_NIM_MHS, nimStr)); try { JSONObject json = jParser.makeHttpRequest(url_update_mhs,"POST", parameter); int success = json.getInt(TAG_SUCCESS); if (success == 1) { return "OK"; } else { return "FAIL"; } } catch (Exception e) { e.printStackTrace(); return "Exception Caught"; } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); pDialog.dismiss(); if(result.equalsIgnoreCase("Exception Caught")) { Toast.makeText(UpdateDeleteActivity.this, "Unable to connect to server,please check your internet connection!", Toast.LENGTH_LONG).show(); } if(result.equalsIgnoreCase("FAIL")) { Toast.makeText(UpdateDeleteActivity.this, "Fail.. Try Again", Toast.LENGTH_LONG).show(); } else { Intent i = null; i = new Intent(UpdateDeleteActivity.this, MainActivity.class); startActivity(i); } } } class DeleteMhsTask extends AsyncTask<String, Void, String> { ProgressDialog pDialog; @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(UpdateDeleteActivity.this); pDialog.setMessage("Mohon Tunggu.."); pDialog.setIndeterminate(true); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... sText) { List<NameValuePair> parameter = new ArrayList<NameValuePair>(); parameter.add(new BasicNameValuePair(TAG_ID_MHS, idStr)); try { JSONObject json = jParser.makeHttpRequest(url_delete_mhs,"POST", parameter); int success = json.getInt(TAG_SUCCESS); if (success == 1) { return "OK"; } else { return "FAIL"; } } catch (Exception e) { e.printStackTrace(); return "Exception Caught"; } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); pDialog.dismiss(); if(result.equalsIgnoreCase("Exception Caught")) { Toast.makeText(UpdateDeleteActivity.this, "Unable to connect to server,please check your internet connection!", Toast.LENGTH_LONG).show(); } if(result.equalsIgnoreCase("FAIL")) { Toast.makeText(UpdateDeleteActivity.this, "Fail.. Try Again", Toast.LENGTH_LONG).show(); } else { Intent i = null; i = new Intent(UpdateDeleteActivity.this, MainActivity.class); startActivity(i); } } } }
Selesai… Kita bisa jalankan aplikasi kita dan update dan delete juga bisa dilakukan.
Langkah 15
Sekarang kita lanjut agar aplikasi kita bisa menambah data mahasiswa ke database. Kita buat dulu activity_create.xml, berikut isinya :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:padding="10dp"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Nama"
android:id="@+id/textView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextNama" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="NIM"
android:id="@+id/textView2"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextNim"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add"
android:id="@+id/buttonAdd"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Selanjutnya, kita buat kelas boundary-nya yaitu CreateActivity.java, kelas ini dibuat extends ActionBarActivity, dan jangan lupa kita definisikan juga setiap TextView, Button, maupun EditText-nya. Berikut kodingnya :
package com.vhiefa.simplecrud;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by Afifatul on 6/18/2015.
*/
public class CreateActivity extends ActionBarActivity{
EditText EditTxtnama, EditTxtnim;
Button addBtn;
String namaStr, nimStr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
EditTxtnama = (EditText) findViewById(R.id.editTextNama);
EditTxtnim = (EditText) findViewById(R.id.editTextNim);
addBtn = (Button) findViewById(R.id.buttonAdd);
}
}
Kita update AndroidManifest.xml agar kelas CreateActivity bisa dipanggil di aplikasi android kita, tambahkan code berikut :
<activity
android:name="com.vhiefa.simplecrud.CreateActivity"
android:label="Tambah Mahasiswa"
android:parentActivityName="com.vhiefa.simplecrud.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.vhiefa.simplecrud.MainActivity" />
</activity>
Sehingga koding di AndroidManifest.xml secara keseluruhan menjadi sebagai berikut :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.vhiefa.simplecrud" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<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="com.vhiefa.simplecrud.CreateActivity"
android:label="Tambah Mahasiswa"
android:parentActivityName="com.vhiefa.simplecrud.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.vhiefa.simplecrud.MainActivity" />
</activity>
<activity
android:name="com.vhiefa.simplecrud.UpdateDeleteActivity"
android:label="Detail Mahasiswa"
android:parentActivityName="com.vhiefa.simplecrud.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.vhiefa.simplecrud.MainActivity" />
</activity>
</application>
</manifest>
Langkah 16
Kita buat agar di activity utama (MainActivity) dapat menampilkan tombol Add di pojok kanan action bar. Caranya kita update dulu main_menu.xml yang berada pada direktori menu. Berikut kodingnya :
<menu 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" tools:context=".MainActivity">
<item android:id="@+id/action_add" android:title="Add"
android:orderInCategory="100" app:showAsAction="always" />
</menu>
Kemudian kita tambahkan kode berikut pada MainActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_add) {
Intent i = new Intent(MainActivity.this, CreateActivity.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
Sehingga secara keseluruhan isi MainActivity.java menjadi sebagai berikut :
package com.vhiefa.simplecrud; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class MainActivity extends ActionBarActivity { ListView list; JSONParser jParser = new JSONParser(); ArrayList<Mahasiswa> daftar_mhs = new ArrayList<Mahasiswa>(); JSONArray daftarMhs = null; String url_read_mhs = "http://api.vhiefa.net76.net/simple_crud/read_mhs.php"; // JSON Node names, ini harus sesuai yang di API public static final String TAG_SUCCESS = "success"; public static final String TAG_MHS = "mahasiswa"; public static final String TAG_ID_MHS = "id_mhs"; public static final String TAG_NAMA_MHS = "nama"; public static final String TAG_NIM_MHS = "nim"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); list = (ListView) findViewById(R.id.listview_mhs); //jalankan ReadMhsTask ReadMhsTask m= (ReadMhsTask) new ReadMhsTask().execute(); list.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int urutan, long id) { //dapatkan data id, nama, nim mahasiswa dan simpan dalam variable string String idmhs = ((TextView) view.findViewById(R.id.id_mhs)).getText().toString(); String nama = ((TextView) view.findViewById(R.id.nama_mhs)).getText().toString(); String nim = ((TextView) view.findViewById(R.id.nim_mhs)).getText().toString(); //varible string tadi kita simpan dalam suatu Bundle, dan kita parse bundle tersebut bersama intent menuju kelas UpdateDeleteActivity Intent i = null; i = new Intent(MainActivity.this, UpdateDeleteActivity.class); Bundle b = new Bundle(); b.putString("id_mhs", idmhs); b.putString("nama_mhs", nama); b.putString("nim_mhs", nim); i.putExtras(b); startActivity(i); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_add) { Intent i = new Intent(MainActivity.this, CreateActivity.class); startActivity(i); return true; } return super.onOptionsItemSelected(item); } class ReadMhsTask extends AsyncTask<String, Void, String> { ProgressDialog pDialog; @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Mohon Tunggu.."); pDialog.setIndeterminate(true); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... sText) { String returnResult = getMhsList(); //memanggil method getMhsList() return returnResult; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); pDialog.dismiss(); if(result.equalsIgnoreCase("Exception Caught")) { Toast.makeText(MainActivity.this, "Unable to connect to server,please check your internet connection!", Toast.LENGTH_LONG).show(); } if(result.equalsIgnoreCase("no results")) { Toast.makeText(MainActivity.this, "Data empty", Toast.LENGTH_LONG).show(); } else { list.setAdapter(new MahasiswaAdapter(MainActivity.this,daftar_mhs)); //Adapter menampilkan data mahasiswa ke dalam listView } } //method untuk memperoleh daftar mahasiswa dari JSON public String getMhsList() { Mahasiswa tempMhs = new Mahasiswa(); List<NameValuePair> parameter = new ArrayList<NameValuePair>(); try { JSONObject json = jParser.makeHttpRequest(url_read_mhs,"POST", parameter); int success = json.getInt(TAG_SUCCESS); if (success == 1) { //Ada record Data (SUCCESS = 1) //Getting Array of daftar_mhs daftarMhs = json.getJSONArray(TAG_MHS); // looping through All daftar_mhs for (int i = 0; i < daftarMhs.length() ; i++){ JSONObject c = daftarMhs.getJSONObject(i); tempMhs = new Mahasiswa(); tempMhs.setMhsId(c.getString(TAG_ID_MHS)); tempMhs.setMhsName(c.getString(TAG_NAMA_MHS)); tempMhs.setMhsNIM(c.getString(TAG_NIM_MHS)); daftar_mhs.add(tempMhs); } return "OK"; } else { //Tidak Ada Record Data (SUCCESS = 0) return "no results"; } } catch (Exception e) { e.printStackTrace(); return "Exception Caught"; } } } }
Langkah 17
Sekarang kita buat AsyncTask di dalam CreateActivity.java untuk menambah data mahasiswa yang bernama CreateMhsTask, berikut kodingnya :
class CreateMhsTask extends AsyncTask<String, String, String> {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(CreateActivity.this);
dialog.setMessage("Tambah Mahasiswa...");
dialog.setIndeterminate(false);
dialog.setCancelable(false);
dialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_NAMA_MHS, namaStr));
params.add(new BasicNameValuePair(TAG_NIM_MHS, nimStr));
// getting JSON Object
// Note that create Post url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_mhs, "POST", params);
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// closing this screen
finish();
} else {
return "gagal_database";
}
} catch (JSONException e) {
e.printStackTrace();
return "gagal_koneksi_or_exception";
}
return "sukses";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.equalsIgnoreCase("gagal_database")){
dialog.dismiss();
Toast.makeText(CreateActivity.this, "Terjadi masalah! Silahkan cek koneksi Anda!", Toast.LENGTH_SHORT).show();
}
else if (result.equalsIgnoreCase("gagal_koneksi_or_exception")){
dialog.dismiss();
Toast.makeText(CreateActivity.this, "Terjadi masalah! Silahkan cek koneksi Anda!", Toast.LENGTH_SHORT).show();
}
else if (result.equalsIgnoreCase("sukses")){
dialog.dismiss();
Intent i = null;
i = new Intent(CreateActivity.this, MainActivity.class);
startActivity(i);
}
}
}
Langkah 18
Kita buat agar ketika button add pada CreateActivity bisa berfungsi sebagaimana mestinya. Tambahkan kode berikut :
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
namaStr = EditTxtnama.getText().toString();
nimStr = EditTxtnim.getText().toString();
new CreateMhsTask().execute();
}
});
Sehingga isi CreateActivity.java secara keseluruhan adalah sebagai berikut :
package com.vhiefa.simplecrud;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Afifatul on 6/18/2015.
*/
public class CreateActivity extends ActionBarActivity{
JSONParser jsonParser = new JSONParser();
String url_create_mhs= "http://api.vhiefa.net76.net/simple_crud/create_mhs.php";
// JSON Node names, ini harus sesuai yang di API
public static final String TAG_SUCCESS = "success";
public static final String TAG_NAMA_MHS = "nama";
public static final String TAG_NIM_MHS = "nim";
EditText EditTxtnama, EditTxtnim;
Button addBtn;
String namaStr, nimStr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
EditTxtnama = (EditText) findViewById(R.id.editTextNama);
EditTxtnim = (EditText) findViewById(R.id.editTextNim);
addBtn = (Button) findViewById(R.id.buttonAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
namaStr = EditTxtnama.getText().toString();
nimStr = EditTxtnim.getText().toString();
new CreateMhsTask().execute();
}
});
}
class CreateMhsTask extends AsyncTask<String, String, String> {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(CreateActivity.this);
dialog.setMessage("Tambah Mahasiswa...");
dialog.setIndeterminate(false);
dialog.setCancelable(false);
dialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_NAMA_MHS, namaStr));
params.add(new BasicNameValuePair(TAG_NIM_MHS, nimStr));
// getting JSON Object
// Note that create Post url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_mhs, "POST", params);
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// closing this screen
finish();
} else {
return "gagal_database";
}
} catch (JSONException e) {
e.printStackTrace();
return "gagal_koneksi_or_exception";
}
return "sukses";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.equalsIgnoreCase("gagal_database")){
dialog.dismiss();
Toast.makeText(CreateActivity.this, "Terjadi masalah! Silahkan cek koneksi Anda!", Toast.LENGTH_SHORT).show();
}
else if (result.equalsIgnoreCase("gagal_koneksi_or_exception")){
dialog.dismiss();
Toast.makeText(CreateActivity.this, "Terjadi masalah! Silahkan cek koneksi Anda!", Toast.LENGTH_SHORT).show();
}
else if (result.equalsIgnoreCase("sukses")){
dialog.dismiss();
Intent i = null;
i = new Intent(CreateActivity.this, MainActivity.class);
startActivity(i);
}
}
}
}
Selesai!!! Sekarang aplikasi kita bisa dijalankan.
Code lengkap dan apk-nya bisa didownload DI SINI
Sekian terimakasih.. I know that I am not that expert, but I just wanna share a little thing that I know. Correct me if I’m wrong. Cheers!
Kalo ada yang kurang jelas atau mau bertanya, langsung saja tinggalkan komentar :)
Kalo ada yang kurang jelas atau mau bertanya, langsung saja tinggalkan komentar :)
This comment has been removed by the author.
ReplyDeletekamu hebat bisa berbagi ilmu walau sedikit tapi bermanfaat buatku ;)
ReplyDeleteTerimakasih :)
DeleteThis comment has been removed by the author.
ReplyDeletehebat maksih ya untuk ilmunya
ReplyDeleteterima kasih ilmunya :D
ReplyDeleteTerimakasih ya kakak atas ilmunya :)
ReplyDeleteSama-samaaaa +naomy, +kapten, +vicky, dan +liyan
ReplyDeleteWhen I run the app, it says data empty and there is no layout. Blank. Were do I go wrong ? Do you think it had something to do with my read_mhs.php file ? Because when I ran the read_mhs.php file on the browser, this pop out -->>
ReplyDelete"Warning: mysql_connect(): Host '31.170.167.193' is not allowed to connect to this MySQL server in /home/u373676347/public_html/simple_crud/db_connect.php on line 30 Host '31.170.167.193' is not allowed to connect to this MySQL server Warning: mysql_close(): no MySQL-Link resource supplied in /home/u373676347/public_html/simple_crud/db_connect.php on line 44"
Oh and thank you btw for posting this tutorial.
Kindly check your db_connect.php file.
DeleteEnsure that u give the right host server name.
kalo sama eclipse sama apa engga sih kodingannya ?
ReplyDeleteSama aja kok
DeleteMbak, saya pake Eclipse, kodingannya ngga ada error, tapi pas di launch malah close program, gmana ngatasinya yah mbak?
DeleteTerimakasih
sorry, may i ask something? kenapa ya HttpEntity, HttpResponse, NameValuePair, ClientProtocolException, UrlEncodedFormEntity, HttpGet, HttpPost, URLEncodedUtils, ConnectTimeoutException, DefaultHttpClient, BasicHttpParams menjadi merah?? bagaimana ya untuk buat supaya dia bisa berfungsi??
ReplyDeleteIni jawabannya ada di hal 1 yang gradle:app..
DeleteSemoga benar.
sorry, may i ask something? kenapa ya HttpEntity, HttpResponse, NameValuePair, ClientProtocolException, UrlEncodedFormEntity, HttpGet, HttpPost, URLEncodedUtils, ConnectTimeoutException, DefaultHttpClient, BasicHttpParams menjadi merah?? bagaimana ya untuk buat supaya dia bisa berfungsi??
ReplyDeletePasti sdk yg dipake udah 23an ya..
DeleteAda saran. tambahin ini kalo masih ma pake Http request...
useLibrary 'org.apache.http.legacy'
di gradle nya, Module:app
Pasti sdk yg dipake udah 23an ya..
DeleteAda saran. tambahin ini kalo masih ma pake Http request...
useLibrary 'org.apache.http.legacy'
di gradle nya, Module:app
ok terima kasih ya atas bantuan ;)
ReplyDeleteterimakasih mbk,, sangat membantu,,, :)
ReplyDeletekalau pake hostinger bukan 000webhost langkah2nya masih sama kan ?
ReplyDeletemakasih banget kak! ini tutorial dengan bahasa yg paling simpel yg pernah aku buka. sukses terus ya kak:)
ReplyDelete