Langkah pertama kita menyiapkan sebuah class Entity, yakni class Contact.java. Didalam kelas ini saya mendeklarasikan kolom2 yang akan ada di dalam database nanti, berikut ini classnya :
package
com.example.sqlitetutorials;
public
class
Contact
{
private
int
id;
private
String name;
private
String telp;
public
Contact()
{
// TODO Auto-generated constructor stub
}
public
Contact(String name, String telp)
{
super
();
this
.name = name;
this
.telp = telp;
}
public
int
getId()
{
return
id;
}
public
void
setId(
int
id)
{
this
.id = id;
}
public
String getName()
{
return
name;
}
public
void
setName(String name)
{
this
.name = name;
}
public
String getTelp()
{
return
telp;
}
public
void
setTelp(String telp)
{
this
.telp = telp;
}
}
Kemudian, kita menyiapkan sebuah class untuk mengHandle database kita,
pada class ini akan berisi operasi CRUD (Create, Read, Update, Delete)
didalam class ini terdapat inner class yang saya extends ke class
SQLiteOpenHelper yang sudah disiapkan oleh android.
package
com.example.sqlitetutorials;
import
android.content.ContentValues;
import
android.content.Context;
import
android.database.Cursor;
import
android.database.SQLException;
import
android.database.sqlite.SQLiteDatabase;
import
android.database.sqlite.SQLiteOpenHelper;
import
android.util.Log;
public
class
DBAdapter
{
private
static
final
String DB_NAME =
"contact_db"
;
private
static
final
int
DB_VER =
1
;
public
static
final
String TABLE_NAME =
"contact"
;
public
static
final
String COL_ID =
"_id"
;
public
static
final
String COL_NAME =
"name"
;
public
static
final
String COL_TELP =
"telp"
;
private
static
final
String TAG =
"ContactDBAdapter"
;
private
DatabaseHelper dbHelper;
private
SQLiteDatabase db;
private
static
final
String DB_CREATE =
"create table contact (_id integer primary key, name text not null, telp text not null);"
;
private
final
Context context;
private
static
class
DatabaseHelper
extends
SQLiteOpenHelper
{
public
DatabaseHelper(Context context)
{
// TODO Auto-generated constructor stub
super
(context, DB_NAME,
null
, DB_VER);
}
@Override
public
void
onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL(DB_CREATE);
}
@Override
public
void
onUpgrade(SQLiteDatabase db,
int
oldVersion,
int
newVersion)
{
// TODO Auto-generated method stub
Log.d(TAG,
"upgrade DB"
);
db.execSQL(
"DROP TABLE IF EXISTS "
+ TABLE_NAME);
onCreate(db);
}
}
public
DBAdapter(Context context)
{
this
.context = context;
// TODO Auto-generated constructor stub
}
public
DBAdapter open()
throws
SQLException
{
dbHelper =
new
DatabaseHelper(context);
db = dbHelper.getWritableDatabase();
return
this
;
}
public
void
close()
{
dbHelper.close();
}
public
void
createContact(Contact contact)
{
ContentValues val =
new
ContentValues();
val.put(COL_NAME, contact.getName());
val.put(COL_TELP, contact.getTelp());
db.insert(TABLE_NAME,
null
, val);
}
public
boolean
deleteContact(
int
id)
{
return
db.delete(TABLE_NAME, COL_ID +
"="
+ id,
null
) >
0
;
}
public
Cursor getAllContact()
{
return
db.query(TABLE_NAME,
new
String[]
{
COL_ID, COL_NAME, COL_TELP
},
null
,
null
,
null
,
null
,
null
);
}
public
Cursor getSingleContact(
int
id)
{
Cursor cursor = db.query(TABLE_NAME,
new
String[]
{
COL_ID, COL_NAME, COL_TELP
}, COL_ID +
"="
+ id,
null
,
null
,
null
,
null
);
if
(cursor !=
null
)
cursor.moveToFirst();
return
cursor;
}
public
boolean
updateContact(Contact contact)
{
ContentValues val =
new
ContentValues();
val.put(COL_NAME, contact.getName());
val.put(COL_TELP, contact.getTelp());
return
db.update(TABLE_NAME, val, COL_ID +
"="
+ contact.getId(),
null
) >
0
;
}
}
Kemudian untuk tampilan, ketika program pertama kali dijalankan , akan
muncul daftar contact yang ada, jika tidak ada/ belum ada contact yang
ditambahkan maka akan menampilkan teks empty data, selain itu saya juga
menggunakan menu context yang dapat diakses user dengan menekan tombol
menu pada handset, dengan menekan tombol menu maka akan muncul pilihan
untuk menambah data Contact
package
com.example.sqlitetutorials;
import
android.os.Bundle;
import
android.app.Activity;
import
android.content.Intent;
import
android.database.Cursor;
import
android.support.v4.widget.SimpleCursorAdapter;
import
android.view.Menu;
import
android.view.MenuItem;
import
android.view.View;
import
android.widget.AdapterView;
import
android.widget.AdapterView.OnItemClickListener;
import
android.widget.EditText;
import
android.widget.ListView;
public
class
MainActivity
extends
Activity
implements
OnItemClickListener
{
public
static
final
String KEY_ID =
"_id"
;
private
static
final
int
INSERT_ID = Menu.FIRST;
EditText empty;
private
ListView listview;
private
DBAdapter db;
@Override
protected
void
onCreate(Bundle savedInstanceState)
{
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db =
new
DBAdapter(
this
);
db.open();
listview = (ListView) findViewById(R.id.list);
listview.setEmptyView(findViewById(R.id.empty));
listview.setOnItemClickListener(
this
);
loadData();
}
private
void
loadData()
{
// TODO Auto-generated method stub
Cursor cur = db.getAllContact();
String[] from =
new
String[]
{
DBAdapter.COL_NAME, DBAdapter.COL_TELP
};
int
[] to =
new
int
[]
{
R.id.txtName, R.id.txtPhoneNumber
};
SimpleCursorAdapter adapter =
new
SimpleCursorAdapter(
this
, R.layout.list_adapter, cur, from, to);
listview.setAdapter(adapter);
}
@Override
public
boolean
onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
menu.add(
0
, INSERT_ID,
0
, R.string.menu_add);
return
true
;
}
@Override
public
boolean
onOptionsItemSelected(MenuItem item)
{
// TODO Auto-generated method stub
switch
(item.getItemId())
{
case
INSERT_ID:
startActivity(
new
Intent(MainActivity.
this
, AddContact.
class
));
break
;
}
return
super
.onOptionsItemSelected(item);
}
@Override
public
void
onItemClick(AdapterView<!--?--> arg0, View v,
int
pos,
long
id)
{
// TODO Auto-generated method stub
Bundle bundle =
new
Bundle();
bundle.putLong(KEY_ID, id);
Intent intent =
new
Intent(MainActivity.
this
, EditActivity.
class
);
intent.putExtras(bundle);
db.close();
startActivity(intent);
}
}
dan untuk file xmlnya sebagai 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/list"
android:layout_width
=
"match_parent"
android:layout_height
=
"wrap_content"
>
</
listview
>
<
textview
android:id
=
"@+id/empty"
android:layout_width
=
"match_parent"
android:layout_height
=
"wrap_content"
android:text
=
"Empty Data"
>
</
textview
></
relativelayout
>
dan untuk class yang menangani penambahan data adalah sebagai berikut :
package
com.example.sqlitetutorials;
import
android.app.Activity;
import
android.content.Intent;
import
android.os.Bundle;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.EditText;
public
class
AddContact
extends
Activity
implements
OnClickListener
{
EditText inputName, inputNumber;
Button btnAdd;
DBAdapter db;
@Override
protected
void
onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super
.onCreate(savedInstanceState);
db =
new
DBAdapter(
this
);
db.open();
setContentView(R.layout.add);
inputName = (EditText) findViewById(R.id.inputName);
inputNumber = (EditText) findViewById(R.id.inputNumber);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(
this
);
}
@Override
public
void
onClick(View v)
{
// TODO Auto-generated method stub
switch
(v.getId())
{
case
R.id.btnAdd:
Contact contact =
new
Contact();
contact.setName(inputName.getText().toString());
contact.setTelp(inputNumber.getText().toString());
db.createContact(contact);
startActivity(
new
Intent(AddContact.
this
, MainActivity.
class
));
db.close();
finish();
break
;
default
:
break
;
}
}
}
Nah sekarang, aplikasinya sudah jadi, silahkan jalankan program tersebut di emulator, dan lihat hasilnya.
Sekian dulu untuk saat ini, semoga bermanfaat.
0 Response to "Membuat Aplikasi Android Database Sqlite dengan Tampilan ListVIew"