Untuk memudahkan melihat hasil dari pekerjaan selanjutnya, saya sarankan menginstall sqlite
manager pada eclipse :
1. Copy SQLite Manager pada folder dopins (lokasi eclipse-dropin-sqlitemanager_1.0.0.jar)
2. Pada Eclipse, buka Windows -> Show View -> Other -> File Explorer
Jika emalator belum dijalankan, pada File Explorer akan kosong, pastikan emulator sudah dijalankan jika
ingin melihat tampilan seperti di atas.
3. Setelah itu kita akan membuat project CRUD_SQILITE
4.Buka Eclipse, lalu klik file->New->Other->Android->Android Application Project
5. Isikan pada masing-masing Field (untuk bagian field lain boleh dibuat sesuai keinginan
masing-masing) :
Application Name :CRUD_SQLITE
Package Name : jhointegrity.com
Activity : MainActivity
Layout : main.xml
Ganti Kode pada main.xml menjadi sepertik berikut
Main.xml
Main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00"
android:layout_gravity="center"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/buttonTambahBiodata"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Tambah Biodata" />
<HorizontalScrollView
android:id="@+id/horizontalScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ScrollView
android:id="@+id/verticalScrollView"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<TableLayout
android:id="@+id/tableBiodata"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TableLayout>
</ScrollView>
</HorizontalScrollView>
</LinearLayout>
Setelah itu MainActivity :
package jhointegrity.com;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager.LayoutParams;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
SQLiteHelper sqLiteHelper = new SQLiteHelper(this);
TableLayout tabelBiodata;
Button buttonTambahBiodata;
ArrayList<Button> buttonEdit = new ArrayList<Button>();
ArrayList<Button> buttonDelete = new ArrayList<Button>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tabelBiodata = (TableLayout) findViewById(R.id.tableBiodata);
buttonTambahBiodata = (Button) findViewById(R.id.buttonTambahBiodata);
buttonTambahBiodata.setOnClickListener(this);
TableRow barisTabel = new TableRow(this);
barisTabel.setBackgroundColor(Color.BLUE);
TextView viewHeaderId = new TextView(this);
TextView viewHeaderNama = new TextView(this);
TextView viewHeaderAlamat = new TextView(this);
TextView viewHeaderAction = new TextView(this);
viewHeaderId.setText("ID");
viewHeaderNama.setText("Nama");
viewHeaderAlamat.setText("Alamat");
viewHeaderAction.setText("Action");
viewHeaderId.setPadding(5, 1, 5, 1);
viewHeaderNama.setPadding(5, 1, 5, 1);
viewHeaderAlamat.setPadding(5, 1, 5, 1);
viewHeaderAction.setPadding(5, 1, 5, 1);
barisTabel.addView(viewHeaderId);
barisTabel.addView(viewHeaderNama);
barisTabel.addView(viewHeaderAlamat);
barisTabel.addView(viewHeaderAction);
tabelBiodata.addView(barisTabel, new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
ArrayList<HashMap<String, String>> arrayListBiodata = sqLiteHelper
.tampil_semua_biodata();
if (arrayListBiodata.size() > 0) {
for (int i = 0; i < arrayListBiodata.size(); i++) {
// ambil masing-masing hasmap dari arrayListBiodata
HashMap<String, String> hashMapRecordBiodata = arrayListBiodata.get(i);
// JSONObject jsonChildNode = arrayBiodata.getJSONObject(i);
String name = hashMapRecordBiodata.get("nama");
String alamat = hashMapRecordBiodata.get("alamat");
String id = hashMapRecordBiodata.get("id_biodata");
System.out.println("Nama :" + name);
System.out.println("Alamat :" + alamat);
System.out.println("ID :" + id);
barisTabel = new TableRow(this);
if (i % 2 == 0) {
barisTabel.setBackgroundColor(Color.LTGRAY);
}
TextView viewId = new TextView(this);
viewId.setText(id);
viewId.setPadding(5, 1, 5, 1);
barisTabel.addView(viewId);
TextView viewNama = new TextView(this);
viewNama.setText(name);
viewNama.setPadding(5, 1, 5, 1);
barisTabel.addView(viewNama);
TextView viewAlamat = new TextView(this);
viewAlamat.setText(alamat);
viewAlamat.setPadding(5, 1, 5, 1);
barisTabel.addView(viewAlamat);
buttonEdit.add(i, new Button(this));
buttonEdit.get(i).setId(Integer.parseInt(id));
buttonEdit.get(i).setTag("Edit");
buttonEdit.get(i).setText("Edit");
buttonEdit.get(i).setOnClickListener(this);
barisTabel.addView(buttonEdit.get(i));
buttonDelete.add(i, new Button(this));
buttonDelete.get(i).setId(Integer.parseInt(id));
buttonDelete.get(i).setTag("Delete");
buttonDelete.get(i).setText("Delete");
buttonDelete.get(i).setOnClickListener(this);
barisTabel.addView(buttonDelete.get(i));
tabelBiodata.addView(barisTabel, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
}
}
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.buttonTambahBiodata) {
// Toast.makeText(MainActivity.this, "Button Tambah Data",
// Toast.LENGTH_SHORT).show();
tambahBiodata();
} else {
/*
* Melakukan pengecekan pada data array, agar sesuai dengan index
* masing-masing button
*/
for (int i = 0; i < buttonEdit.size(); i++) {
/* jika yang diklik adalah button edit */
if (view.getId() == buttonEdit.get(i).getId()
&& view.getTag().toString().trim().equals("Edit")) {
//Toast.makeText(MainActivity.this, "Edit : " + // buttonEdit.get(i).getId(), Toast.LENGTH_SHORT).show();
int id = buttonEdit.get(i).getId();
getDataByID(id);
} /* jika yang diklik adalah button delete */
else if (view.getId() == buttonDelete.get(i).getId()
&&
view.getTag().toString().trim().equals("Delete")) {
// Toast.makeText(MainActivity.this, "Delete : " + // buttonDelete.get(i).getId(), Toast.LENGTH_SHORT).show();
int id = buttonDelete.get(i).getId();
deleteBiodata(id);
}
}
}
}
public void deleteBiodata(int id) {
sqLiteHelper.hapus_biodata(id);
/* restart acrtivity */
finish();
startActivity(getIntent());
}
public void getDataByID(int id) {
String namaEdit = null, alamatEdit = null;
HashMap<String, String> hashMapBiodata = sqLiteHelper
.tampil_biodata_berdasarkan_id(id);
for (int i = 0; i < hashMapBiodata.size(); i++) {
namaEdit = hashMapBiodata.get("nama");
alamatEdit = hashMapBiodata.get("alamat");
}
LinearLayout layoutInput = new LinearLayout(this);
layoutInput.setOrientation(LinearLayout.VERTICAL);
// buat id tersembunyi di alertbuilder
final TextView viewId = new TextView(this);
viewId.setText(String.valueOf(id));
viewId.setTextColor(Color.TRANSPARENT);
layoutInput.addView(viewId);
final EditText editNama = new EditText(this);
editNama.setText(namaEdit);
layoutInput.addView(editNama);
final EditText editAlamat = new EditText(this);
editAlamat.setText(alamatEdit);
layoutInput.addView(editAlamat);
AlertDialog.Builder builderEditBiodata = new AlertDialog.Builder(this);
builderEditBiodata.setTitle("Update Biodata");
builderEditBiodata.setView(layoutInput);
builderEditBiodata.setPositiveButton("Update",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String nama = editNama.getText().toString();
String alamat = editAlamat.getText().toString();
System.out.println("Nama : " + nama + " Alamat : " + alamat);
sqLiteHelper.update_biodata(Integer.parseInt(viewId
.getText().toString()),
editNama.getText()
.toString(),
editAlamat.getText().toString());
/* restart acrtivity */
finish();
startActivity(getIntent());
}
});
builderEditBiodata.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builderEditBiodata.show();
}
public void tambahBiodata() {
/* layout akan ditampilkan pada AlertDialog */
LinearLayout layoutInput = new LinearLayout(this);
layoutInput.setOrientation(LinearLayout.VERTICAL);
final EditText editNama = new EditText(this);
editNama.setHint("Nama");
layoutInput.addView(editNama);
final EditText editAlamat = new EditText(this);
editAlamat.setHint("Alamat");
layoutInput.addView(editAlamat);
AlertDialog.Builder builderInsertBiodata = new AlertDialog.Builder(this);
builderInsertBiodata.setTitle("Insert Biodata");
builderInsertBiodata.setView(layoutInput);
builderInsertBiodata.setPositiveButton("Insert",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String nama = editNama.getText().toString();
String alamat = editAlamat.getText().toString();
System.out.println("Nama : " + nama + " Alamat: " + alamat);
sqLiteHelper.tambah_biodata(nama, alamat);
/* restart acrtivity */
finish();
startActivity(getIntent());
}
});
builderInsertBiodata.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builderInsertBiodata.show();
}
}
Setelah Mebuat MainActivity.java sekarang SQLiteHelper.java, berikut source code SQLiteHelper.java :
package jhointegrity.com;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLiteHelper extends SQLiteOpenHelper {
private static final String nama_database = "database_pemain.db";
private static final int versi_database = 1;
private static final String query_buat_tabel_biodata_pemain = "CREATE TABLE IF NOT EXISTS tabel_biodata(id_biodata INTEGER PRIMARY KEY AUTOINCREMENT, nama TEXT,alamat TEXT)";
private static final String query_hapus_tabel_biodata_pemain = "DROP TABLE IF EXISTS query_buat_tabel_biodata_pemain";
public SQLiteHelper(Context context) {
super(context, nama_database, null, versi_database);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(query_buat_tabel_biodata_pemain);
System.out.println("tabel_biodata sudah dibuat");
}
@Override
public void onUpgrade(SQLiteDatabase database, int versi_lama,
int versi_baru) {
database.execSQL(query_hapus_tabel_biodata_pemain);
onCreate(database);
}
public void tambah_biodata(String nama, String alamat) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("nama", nama);
values.put("alamat", alamat);
database.insert("tabel_biodata", null, values);
database.close();
}
public ArrayList<HashMap<String, String>> tampil_semua_biodata() {
// deklarasikan sebuah arraylist yang bisa menampung hashmap
ArrayList<HashMap<String, String>> arrayListBiodata = new ArrayList<HashMap<String,
String>>();
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM tabel_biodata", null);
// kursor langsung diarkan ke posisi paling awal data pada tabel_biodata
if (cursor.moveToFirst()) {
do {
// deklarasikan sebuah hashmap, yang bisa menamp
HashMap<String, String> hashMapBiodata = new HashMap<String, String>();
// masukkan masing-masing field dari tabel_biodata ke dalam hashMapBiodata
//pastikan id_biodata, nama dan alamat sama persis dengan field yang ada pada tabel_biodata
hashMapBiodata.put("id_biodata", cursor.getString(0));
hashMapBiodata.put("nama", cursor.getString(1));
hashMapBiodata.put("alamat", cursor.getString(2));
// masukkan hashMapBiodata ke dalam arrayListBiodata
arrayListBiodata.add(hashMapBiodata);
} while (cursor.moveToNext());
}
return arrayListBiodata;
}
public int update_biodata(int id, String nama, String alamat) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues recordBiodata = new ContentValues();
recordBiodata.put("nama", nama);
recordBiodata.put("alamat", alamat);
return database.update("tabel_biodata", recordBiodata, "id_biodata=" + id, null);
}
public void hapus_biodata(int id) {
SQLiteDatabase database = this.getWritableDatabase();
database.execSQL("DELETE FROM tabel_biodata WHERE id_biodata='" + id+ "'");
database.close();
}
public HashMap<String, String> tampil_biodata_berdasarkan_id(int id) {
SQLiteDatabase database = this.getReadableDatabase();
HashMap<String, String> hashMapBiodata = new HashMap<String, String>();
Cursor cursor = database.rawQuery("SELECT * FROM tabel_biodata WHERE id_biodata="
+ id + "", null);
if (cursor.moveToFirst()) {
do {
hashMapBiodata.put("id_biodata", cursor.getString(0));
hashMapBiodata.put("nama", cursor.getString(1));
hashMapBiodata.put("alamat", cursor.getString(2));
} while (cursor.moveToNext());
}
return hashMapBiodata;
}
}
Jalankan Run dengan shourcut CTRL+F11 atau klik Kanan package > Runa As > Android Projeck. Lihat Hasilnya Seperti Dibawah Ini :
0 komentar:
Posting Komentar