Android menyediakan beberapa cara untuk menyimpan data pengguna dan data aplikasi. Salah satunya ialah dengan menggukanan Database SQLite yang di dukung penuh oleh Android. SQLite adalah database yang sangat ringan yang include dalam Sistem Operasi Android. Dalam tutorial ini saya akan membahas bagaimana menulis class untuk menangani semua operasi SQLite.
Tutorial ini akan menggunakan contoh data penyimpanan buku kontak dalam database SQLite. Dalam membuat database menggunakan method openOrCreateDatabase dengan nama database dan mode sebagai parameter. Dengan mengembalikan instance dari sebuah database SQLite pada sintaks berikut
SQLiteDatabse mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);
Kita dapat membuat tabel atau memasukkan data ke dalam tabel menggunakan execSQL method didefinisikan dalam kelas SQLiteDatabase. Sintaksnya seperti berikut.
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
Untuk mengelola semua aplikasi yang berkaitan dengan database, di buatkan class khusus yang di beri nama SQLiteOpenHelper
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}
Ok. Baiklah berikut adalah contoh aplikasi dengan menggunakan database SQLite. Ini adalah aplikasi kontak yang memungkinkan kita untuk menambahkan, menghapus dan memodifikasi kontak. Untuk membuat aplikasi ini, berikut tutorialnya.
1. Buat Project baru dan atur seperti gambar berikut
2. Klik
Next sampai
Finish dan biarkan default aja.
3. Masuk ke directory "
res/values/strings.xml" Sesuaikan dengan kode berikut.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Buku Kontak</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="masukkan">Kontak Baru</string>
<string name="edit">Edit</string>
<string name="hapus">Hapus</string>
<string name="title_activity_display_contact">DisplayContact</string>
<string name="nama">Nama</string>
<string name="phone">Telp</string>
<string name="email">Email</string>
<string name="alamat">Alamat</string>
<string name="kota">Kota</string>
<string name="simpan">Simpan</string>
<string name="hapusKontakYakin">Anda yakin ingin menghapus kontak ini.</string>
<string name="ya">Ya</string>
<string name="tidak">Tidak</string>
</resources>
4. Buat 2 directory baru di "
res/menu/" beri nama dengan "
display_contact.xml" dan "
mainmenu.xml"
5. Buka directory "
res/menu/display_contact.xml" sesuaikan dengan code berikut.
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/Edit_Contact"
android:orderInCategory="100"
android:title="@string/edit"/>
<item
android:id="@+id/Delete_Contact"
android:orderInCategory="100"
android:title="@string/hapus"/>
</menu>
6. Buka directory "
res/menu/mainmenu.xml" atur codenya seperti berikut
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/item1"
android:icon="@drawable/ic_launcher"
android:title="@string/masukkan"
android:showAsAction="ifRoom|withText">
</item>
</menu>
7. Buka directory "
res/layout/activity_main.xml" sesuaikan dengan code berikut..
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>
</RelativeLayout>
8. Buat directory baru di "
res/layout" berinama dengan "
activity_display_contact.xml" lalu sesuaikan dengan code berikut.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DisplayContact" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
>
<EditText
android:id="@+id/editTextNama"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="82dp"
android:ems="10"
android:inputType="text" >
</EditText>
<EditText
android:id="@+id/editTextEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextAlamat"
android:layout_below="@+id/editTextAlamat"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="textEmailAddress" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextNama"
android:layout_alignParentLeft="true"
android:text="@string/nama"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextKota"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="@string/simpan" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView1"
android:text="@string/email"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextPhone"
android:layout_alignLeft="@+id/textView1"
android:text="@string/phone"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView5"
android:text="@string/alamat"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editTextKota"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editTextNama"
android:layout_below="@+id/editTextEmail"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="text" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editTextKota"
android:layout_alignBottom="@+id/editTextKota"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/editTextEmail"
android:text="@string/kota"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editTextAlamat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextNama"
android:layout_below="@+id/editTextPhone"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editTextPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextAlamat"
android:layout_below="@+id/editTextNama"
android:ems="10"
android:inputType="phone|text" />
</RelativeLayout>
</ScrollView>
9. Buka "
src/com.ahmadsahidin.bukukontak/MainActivity.java" sesuaikan dengan code berikut
package com.ahmadsahidin.bukukontak;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.AddressBook.MESSAGE";
private ListView obj;
DBHelper mydb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
//adding it to the list view.
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),com.ahmadsahidin.bukukontak.DisplayContact.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.item1:
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),com.ahmadsahidin.bukukontak.DisplayContact.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}
10. Buat 2 class baru di "
src/com.ahmadsahidin.bukukontak" berinama dengan "
DisplayContact.java" dan "
DBHelper.java"
11. Buka "
src/com.ahmadsahidin.bukukontak/DisplayContact.java" atur kodenya seperti berikut
package com.ahmadsahidin.bukukontak;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class DisplayContact extends Activity {
int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;
TextView nama ;
TextView phone;
TextView email;
TextView alamat;
TextView kota;
int id_To_Update = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
nama = (TextView) findViewById(R.id.editTextNama);
phone = (TextView) findViewById(R.id.editTextPhone);
alamat = (TextView) findViewById(R.id.editTextAlamat);
email = (TextView) findViewById(R.id.editTextEmail);
kota = (TextView) findViewById(R.id.editTextKota);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String namaAnda = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
String telpon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));
String emailAnda = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));
String alamatAnda = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));
String kotaAnda = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));
if (!rs.isClosed())
{
rs.close();
}
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
nama.setText((CharSequence)namaAnda);
nama.setFocusable(false);
nama.setClickable(false);
phone.setText((CharSequence)telpon);
phone.setFocusable(false);
phone.setClickable(false);
email.setText((CharSequence)emailAnda);
email.setFocusable(false);
email.setClickable(false);
alamat.setText((CharSequence)alamatAnda);
alamat.setFocusable(false);
alamat.setClickable(false);
kota.setText((CharSequence)kotaAnda);
kota.setFocusable(false);
kota.setClickable(false);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
}
else{
getMenuInflater().inflate(R.menu.main, menu);
}
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
nama.setEnabled(true);
nama.setFocusableInTouchMode(true);
nama.setClickable(true);
phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);
email.setEnabled(true);
email.setFocusableInTouchMode(true);
email.setClickable(true);
alamat.setEnabled(true);
alamat.setFocusableInTouchMode(true);
alamat.setClickable(true);
kota.setEnabled(true);
kota.setFocusableInTouchMode(true);
kota.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.hapusKontakYakin)
.setPositiveButton(R.string.ya, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),com.ahmadsahidin.bukukontak.MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.tidak, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Anda Yakin");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view)
{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
if(mydb.updateContact(id_To_Update,nama.getText().toString(), phone.getText().toString(), email.getText().toString(), alamat.getText().toString(), kota.getText().toString())){
Toast.makeText(getApplicationContext(), "Terupdate", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),com.ahmadsahidin.bukukontak.MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(), "Tidak Terupadate", Toast.LENGTH_SHORT).show();
}
}
else{
if(mydb.insertContact(nama.getText().toString(), phone.getText().toString(), email.getText().toString(), alamat.getText().toString(), kota.getText().toString())){
Toast.makeText(getApplicationContext(), "selesai", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "belum selesai", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),com.ahmadsahidin.bukukontak.MainActivity.class);
startActivity(intent);
}
}
}
}
12. Buka "
res/com.ahmadsahidin.bukukontak/DBHelper.java" sesuaikan dengan kode berikut..
package com.ahmadsahidin.bukukontak;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "nama";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_STREET = "alamat";
public static final String CONTACTS_COLUMN_CITY = "kota";
public static final String CONTACTS_COLUMN_PHONE = "phone";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, nama text,phone text,email text, alamat text,kota text)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String nama, String phone, String email, String alamat,String kota)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("nama", nama);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("alamat", alamat);
contentValues.put("kota", kota);
db.insert("contacts", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String nama, String phone, String email, String alamat,String kota)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("nama", nama);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("alamat", alamat);
contentValues.put("kota", kota);
db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList getAllCotacts()
{
ArrayList array_list = new ArrayList();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
13. Buka
AndroidManifest.xml sesuaikan dengan code berikut
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ahmadsahidin.bukukontak"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.ahmadsahidin.bukukontak.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.ahmadsahidin.bukukontak.DisplayContact"
android:label="@string/title_activity_display_contact" >
</activity>
</application>
</manifest>
14. Terakhir jalankan aplikasinya. Berikut tampilan hasil jadinya.
Sekian tutorial tentang database SQLite ini, semoga berguna dan bermanfaat.
src: tutorialspoint.com