Hallo netCitizen, apakabar?
Tulisan kali ini saya akan coba share mengenai aplikasi mobile android untuk men-sensus warga di setiap RT :). Ya benar, aplikasi ini dibuat untuk memudahkan RT dalam mengetahui data warganya dengan mudah dan disimpan dalam database SQLite di perangkat mobilenya.
Ok langsung mulai saja, seperti biasa buat project android baru di eclipse. Seperti contoh di bawah ini:
Selanjutnya adalah membuat DBAdapter yang difungsikan untuk berinteraksi dengan database, database yang digunakan adalah SQLite versi 3. Berikut adalah script pada file DBAdapter.java
package com.example.sensusrt;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String DATABASE_PATH="/data/data/com.example.sensusrt/databases/";
private static final String DATABASE_NAME="db_sensus.sqlite3";
private static final int DATABASE_VERSION=3;
private static final String TABLE_PENDUDUK = "tbl_penduduk";
private static final String TABLE_PENDUDUK_noKTP = "noKTP";
private static final String TABLE_PENDUDUK_nama = "nama";
private static final String TABLE_PENDUDUK_jk = "jk";
private static final String TABLE_PENDUDUK_tempatLahir = "tempatLahir";
private static final String TABLE_PENDUDUK_tglLahir = "tanggalLahir";
private static final String TABLE_PENDUDUK_statusMenikah = "statusMenikah";
private static final String TABLE_PENDUDUK_noTelp = "noTelp";
private final Context context;
private DatabaseHelper dbHelper;
private SQLiteDatabase db; //private static final String tbl_create1 = "ALTER TABLE 'main'.'tbl_penduduk' RENAME TO '_tbl_penduduk_old_20140728';";
private static final String tbl_create = "CREATE TABLE 'tbl_penduduk' ('noKTP' VARCHAR(40) NOT NULL,'nama' VARCHAR(70) NOT NULL,'jk' VARCHAR(1) NOT NULL,'tempatLahir' VARCHAR(90) NOT NULL,'tanggalLahir' DATE NOT NULL,'statusMenikah' VARCHAR(1),'noTelp' VARCHAR(15),'tglInput' DATE DEFAULT (CURRENT_DATE),PRIMARY KEY ('noKTP' ASC));";
//public static final String KEY_NPM = "npm";
//public static final String KEY_NAMA = "nama";
//public static final String KEY_JURUSAN= "jurusan";
//public static final String KEY_SEMESTER= "semester";
public DBAdapter(Context ctx) {
this.context = ctx;
dbHelper = new DatabaseHelper(this.context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//do nothing. The event is handled by the "prepareDatabase" method.
// db.execSQL(tbl_create);
try {
db.execSQL(tbl_create);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//do nothing. The event is handled by the "prepareDatabase" method.
Log.w(DatabaseHelper.class.getName(),"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PENDUDUK);
onCreate(db);
}
}
public DBAdapter open() throws SQLException {
db = dbHelper.getWritableDatabase(); //or getReadableDatabase() for read only access
return this;
}
public void close() {
dbHelper.close();
}
private boolean checkDatabase() {
SQLiteDatabase checkDb = null;
try {
checkDb = SQLiteDatabase.openDatabase(DATABASE_PATH + DATABASE_NAME,
null, SQLiteDatabase.OPEN_READONLY);
}
catch (SQLiteException ex) {
//Database does not exist yet
}
if(checkDb != null)
checkDb.close();
return checkDb != null ? true : false;
}
private void copyDatabase() throws IOException {
//get the SQLite database in the "assets" folder
InputStream input = context.getAssets().open(DATABASE_NAME);
//copy to the device path
OutputStream output = new FileOutputStream(DATABASE_PATH + DATABASE_NAME);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer))>0)
output.write(buffer,0,length); output.flush();
output.close();
input.close();
}
public void prepareDatabase() {
if(this.checkDatabase()) {
//do nothing. The database already exists
}
else {
dbHelper.getReadableDatabase();
try {
this.copyDatabase() ;
}
catch (IOException ex) {
throw new Error ("Error copying database");
}
}
}
public long insertPenduduk(String noKTP, String nama, String jk, String tempatLahir, String tanggalLahir, String statusNikah, String noTelp) {
ContentValues initialValues = new ContentValues();
initialValues.put(TABLE_PENDUDUK_noKTP, noKTP);
initialValues.put(TABLE_PENDUDUK_nama, nama );
initialValues.put(TABLE_PENDUDUK_jk, jk);
initialValues.put(TABLE_PENDUDUK_tempatLahir,tempatLahir); initialValues.put(TABLE_PENDUDUK_tglLahir,tanggalLahir); initialValues.put(TABLE_PENDUDUK_statusMenikah,statusNikah); initialValues.put(TABLE_PENDUDUK_noTelp,noTelp);
return db.insert(TABLE_PENDUDUK, null, initialValues);
}
//---updates a data--
public boolean updatePenduduk(String rowId, String noKTP, String nama, String jk, String tempatLahir, String tanggalLahir, String statusNikah, String noTelp) {
ContentValues initialValues = new ContentValues();
initialValues.put(TABLE_PENDUDUK_noKTP, noKTP);
initialValues.put(TABLE_PENDUDUK_nama, nama );
initialValues.put(TABLE_PENDUDUK_jk, jk);
initialValues.put(TABLE_PENDUDUK_tempatLahir,tempatLahir); initialValues.put(TABLE_PENDUDUK_tglLahir,tanggalLahir); initialValues.put(TABLE_PENDUDUK_statusMenikah,statusNikah); initialValues.put(TABLE_PENDUDUK_noTelp,noTelp);
return db.update(TABLE_PENDUDUK, initialValues, TABLE_PENDUDUK_noKTP+ "='" + rowId+"'", null)> 0;
}
//---deletes a particular contact--
public boolean deletePenduduk(long rowId){
return db.delete(TABLE_PENDUDUK, TABLE_PENDUDUK_noKTP + "=" + rowId, null) > 0;
}
//This is custom function to retrieve all product
public Cursor getAllPenduduk() {
return db.query(TABLE_PENDUDUK, new String[] {
TABLE_PENDUDUK_noKTP, TABLE_PENDUDUK_nama, TABLE_PENDUDUK_jk, TABLE_PENDUDUK_tempatLahir, TABLE_PENDUDUK_tglLahir, TABLE_PENDUDUK_statusMenikah, TABLE_PENDUDUK_noTelp
}, null, null, null, null, TABLE_PENDUDUK_nama);
}
//---retrieves a particular contact--
public Cursor getDataPenduduk(String noKTP) throws SQLException
{
Cursor mCursor = db.query(true, TABLE_PENDUDUK, new String[] {TABLE_PENDUDUK_noKTP, TABLE_PENDUDUK_nama, TABLE_PENDUDUK_jk, TABLE_PENDUDUK_tempatLahir, TABLE_PENDUDUK_tglLahir, TABLE_PENDUDUK_statusMenikah, TABLE_PENDUDUK_noTelp}, TABLE_PENDUDUK_noKTP+ "=" + noKTP, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public int jumlahData (String tanggal){
Cursor c = dbHelper.getReadableDatabase().rawQuery("SELECT " + TABLE_PENDUDUK_noKTP+ " from tbl_penduduk where tglInput between '1945-01-01' and '" + tanggal + "' ", null);
return c.getCount();
}
public int jumlahDataByJk (String tanggal, String jk){
Cursor c = dbHelper.getReadableDatabase().rawQuery("SELECT jk from tbl_penduduk where jk='"+jk+"' and (tglInput between '1945-01-01' and '" + tanggal + "')", null);
return c.getCount();
}
}
Berikut adalah script dari fragment_main.xml.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"Selanjutnya adalah script untuk file MainActivity.java
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="com.example.sensusrt.MainActivity$PlaceholderFragment" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/judulAplikasi" />
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="@string/LDataPertanggal" />
<DatePicker
android:id="@+id/DatePertanggal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:calendarViewShown="false"
android:minDate="01-01-1945"
android:spinnersShown="true"
android:startYear="1945" />
<Button
android:id="@+id/bResfrehData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/refreshData" />
<TextView
android:id="@+id/tRangkuman"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="@+id/bLihatData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/bLihatData" />
<Button
android:id="@+id/bTambahData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/bTambah" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
package com.example.sensusrt;dibawah ini adalah gambar ketika main activity di jalankan.
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public Button bTambahData, bRefreshData, bLihatData;
public TextView tRangkuman;
public DatePicker tanggalData;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
bTambahData = (Button) rootView.findViewById(R.id.bTambahData);
bTambahData.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent seninIntent = new Intent(getActivity(),FormPendataan.class);
startActivityForResult(seninIntent, 0);
}
});
bRefreshData = (Button) rootView.findViewById(R.id.bResfrehData);
bRefreshData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
refreshData();
}
});
bLihatData = (Button) rootView.findViewById(R.id.bLihatData);
bLihatData.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent seninIntent = new Intent(getActivity(),LihatDataActivity.class);
startActivityForResult(seninIntent, 0);
}
});
tRangkuman = (TextView) rootView.findViewById(R.id.tRangkuman);
tanggalData = (DatePicker) rootView.findViewById(R.id.DatePertanggal);
tanggalData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
refreshData();
}
});
DBAdapter db = new DBAdapter(getActivity()); db.prepareDatabase();
refreshData();
return rootView;
}
public void refreshData(){ //REFRESH DATA DARI DATABASE----------------
DBAdapter db = new DBAdapter(getActivity());
try {
db.open(); String tanggal = functionSendiri.formatTanggal(Integer.toString(tanggalData.getYear()), Integer.toString(tanggalData.getMonth()), Integer.toString(tanggalData.getDayOfMonth()));
int jumlahL = db.jumlahDataByJk(tanggal, "L");
int jumlahP = db.jumlahDataByJk(tanggal, "P");
int jumlahSemuanya = db.jumlahData(tanggal);
tRangkuman.setText("Banyaknya data yang sudah masuk : " + Integer.toString(jumlahSemuanya) +". Laki laki ada " + Integer.toString(jumlahL) + " orang. Perempuan ada " + Integer.toString(jumlahP) + " orang.");
/*if(c.moveToFirst()){
do {
Toast.makeText(getActivity(), c.getString(0), Toast.LENGTH_SHORT).show();
} while (c.moveToNext());
}*/
} catch (SQLException e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
// TODO: handle exception
}
}
}
}
Selanjutnya adalah membuat form untuk menambah dan mengedit data, buat activity baru dengan nama FormPendataan berikut adalah script untuk layout fragment_form_pendataan.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"Selanjutnya adalah script untuk FormPendataan.java:
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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="com.example.sensusrt.FormPendataan$PlaceholderFragment" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="@+id/LinearLayout2"
android:layout_width="match_parent"
android:layout_height="556dp"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tNoKtp" />
<EditText
android:id="@+id/tNoKTP"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="@string/LNama" />
<EditText
android:id="@+id/tNama"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text"
android:singleLine="true" />
<TextView
android:id="@+id/tRangkuman"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="17dp"
android:text="@string/lJenisKelamin" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/opLaki"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/opLaki" />
<RadioButton
android:id="@+id/opPerempuan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/opPerempuan" />
</RadioGroup>
<TextView
android:id="@+id/lNama"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:text="@string/LTempatLahir" />
<EditText
android:id="@+id/tTempatLahir"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text"
android:singleLine="true" />
<DatePicker
android:id="@+id/tTanggalLahir"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:calendarViewShown="false"
android:spinnersShown="true" />
<TextView
android:id="@+id/lJk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:text="@string/LStatusNikah" />
<RadioGroup
android:id="@+id/radioGroup2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/opNikah"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/opNikah" />
<RadioButton
android:id="@+id/opLajang"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/opLajang" />
</RadioGroup>
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:text="@string/LNoTelp" />
<EditText
android:id="@+id/tNoTelp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="phone"
android:singleLine="true" />
<Button
android:id="@+id/bSimpan"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/LkIRIM" />
</LinearLayout>
</ScrollView>
</LinearLayout>
package com.example.sensusrt;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class FormPendataan extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form_pendataan);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.form_pendataan, 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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public Button bSimpan;
public TextView tNoKTP, tNama, tTempatLahir, tNoTelp;
public RadioGroup radioJk, radioStatusNikah;
public RadioButton opLaki, opPerempuan, opNikah, opLajang;
public DatePicker tglLahir;
public String statusNikah, jk, tanggalLahir;
private boolean lagiEdit=false;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_form_pendataan, container, false);
final DBAdapter db = new DBAdapter(getActivity());
db.open();
tNoKTP = (TextView) rootView.findViewById(R.id.tNoKTP);
tNama = (TextView) rootView.findViewById(R.id.tNama);
tNoTelp = (TextView) rootView.findViewById(R.id.tNoTelp);
tTempatLahir = (TextView) rootView.findViewById(R.id.tTempatLahir);
tglLahir = (DatePicker) rootView.findViewById(R.id.tTanggalLahir);
radioJk = (RadioGroup) rootView.findViewById(R.id.radioGroup1);
opLaki = (RadioButton) rootView.findViewById(R.id.opLaki);
opPerempuan = (RadioButton) rootView.findViewById(R.id.opPerempuan);
radioStatusNikah = (RadioGroup) rootView.findViewById(R.id.radioGroup2);
opNikah = (RadioButton) rootView.findViewById(R.id.opNikah);
opLajang = (RadioButton) rootView.findViewById(R.id.opLajang);
bSimpan = (Button) rootView.findViewById(R.id.bSimpan);
bSimpan.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
switch (radioJk.getCheckedRadioButtonId()) {
case R.id.opPerempuan:
jk="P";
break;
default:
jk="L";
break;
}
switch (radioStatusNikah.getCheckedRadioButtonId()) {
case R.id.opNikah:
statusNikah = "M";
break;
default:
statusNikah = "L";
break;
}
tanggalLahir = functionSendiri.formatTanggal(Integer.toString(tglLahir.getYear()) , Integer.toString(tglLahir.getMonth()), Integer.toString(tglLahir.getDayOfMonth()));
if(tNoKTP.getText().equals("")||tNama.getText().equals("")){
Toast.makeText(getActivity(), "Maaf data yang anda input tidak lengkap",Toast.LENGTH_SHORT).show(); }else{
long hasil=3;boolean hasilEdit=true;
if(lagiEdit==false){
hasil= db.insertPenduduk(tNoKTP.getText().toString(), tNama.getText().toString(), jk, tTempatLahir.getText().toString(), tanggalLahir, statusNikah, tNoTelp.getText().toString());
}else{
hasilEdit = db.updatePenduduk(tNoKTP.getText().toString(),tNoKTP.getText().toString(), tNama.getText().toString(), jk, tTempatLahir.getText().toString(), tanggalLahir, statusNikah, tNoTelp.getText().toString());
}
if(hasil==-1 || hasilEdit==false){
Toast.makeText(getActivity(), "Data gagal disimpan "+hasilEdit+hasil,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "Data berhasil disimpan",Toast.LENGTH_SHORT).show();
tNoKTP.setText("");
tNama.setText("");
tTempatLahir.setText("");
tNoTelp.setText("");
}
}
}
});
String noKTP=functionSendiri.getExtraVariable("noKTP", getActivity().getIntent());
tNoKTP.setText(noKTP);
if(!noKTP.equals("")){
lagiEdit=true;
try {
Cursor c = db.getDataPenduduk(noKTP);
tNoKTP.setText(c.getString(0));
tNama.setText(c.getString(1));
if(c.getString(2)=="L"){
opLaki.setChecked(true);
}else{
opPerempuan.setChecked(true);
}
tTempatLahir.setText(c.getString(3));
if(c.getString(5)=="M"){
opNikah.setChecked(true);
}else{
opLajang.setChecked(true);
}
tNoTelp.setText(c.getString(6));
tNoKTP.setEnabled(false);
} catch (SQLException e) {
// TODO: handle exception
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}else{
lagiEdit=false;
}
return rootView;
}
}
}
Berikut tampilan form setelah di jalankan:
Form pendataan akan muncul setelah mengklik tombol Tambah yang ada di form utama.
Selanjutnya adalah membuat form untuk menampilkan data yang sudah diinput (lihat data), buat activity baru dengan nama LihatData. Dan berikut adalah script untuk layout fragment_lihat_data.xml.
<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="com.example.sensusrt.LihatDataActivity$PlaceholderFragment" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tampilData" />
<ListView
android:id="@+id/listData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1" >
</ListView>
</RelativeLayout>
dan berikut adalah script untuk file LihatDataActivity.java.
package com.example.sensusrt;
import java.util.ArrayList;
import java.util.Arrays;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class LihatDataActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lihat_data);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.lihat_data, 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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public ListView listData;
private ArrayList<String> listItems = new ArrayList<String>(Arrays.asList(""));
private ArrayAdapter<String> adapter;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_lihat_data,
container, false);
listData = (ListView) rootView.findViewById(R.id.listData);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, listItems);
listData.setAdapter(adapter);
listData.setTextFilterEnabled(true);
adapter.setNotifyOnChange(true);
adapter.clear();
//String[] datanya = {};
DBAdapter db = new DBAdapter(getActivity());
try {
db.open(); Cursor c = db.getAllPenduduk();
if(c.moveToFirst()){
do {
adapter.add(c.getString(1).toString()+"-"+c.getString(0).toString());
} while (c.moveToNext());
adapter.notifyDataSetChanged();
}
} catch (SQLException e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
// TODO: handle exception
}
listData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
//int itemke = position;
String itemText = (String) listData.getItemAtPosition(position);
Toast.makeText(getActivity(), "Anda mengklik " + itemText, Toast.LENGTH_LONG).show();
String[] noKtp = itemText.split("-");
//Toast.makeText(getActivity(), Integer.toString(noKtp.length), Toast.LENGTH_LONG).show();
if(noKtp.length>0){
Intent i = new Intent(getActivity(),FormDetilActivity.class);
//startActivityForResult(SeninIntent, 0);
//Toast.makeText(getActivity(), noKtp[1].toString(), Toast.LENGTH_LONG).show();
i.putExtra("noKTP", noKtp[1].toString());
startActivity(i);
}
}
});
return rootView;
}
}
}
Berikut adalah tampilan dari form LihatData setelah dijalankan.
Di form ini juga pengguna(Pak RT), bisa mencari data penduduk dengan mengetikan nama atau No. KTP yang diinginkan. Maka program dengan otomatis akan mencari data tersebut.
Untuk melihat detil dari data penduduk yang ditampilkan, pengguna tinggal mengklik (touch) data penduduk yang dinginkan. maka akan muncul detil data penduduk yang diklik tadi pada form detil penduk dari activity FormDetilActivity.
Script dari layout fragment_form_detil.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"Kemudian ini script dari FormDetilActivity.java
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="com.example.sensusrt.FormDetilActivity$PlaceholderFragment" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lLihatDetil" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="22dp"
android:text="@string/tNoKtp" />
<TextView
android:id="@+id/lNoKTP"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:text="@string/LNama" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/lNoKTP"
android:layout_below="@+id/lNoKTP"
android:layout_marginTop="14dp"
android:text="@string/LNama" />
<TextView
android:id="@+id/lNama"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView3"
android:layout_below="@+id/textView3"
android:text="@string/LNama" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/lNama"
android:layout_below="@+id/lNama"
android:layout_marginTop="16dp"
android:text="@string/lJenisKelamin" />
<TextView
android:id="@+id/lJk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView4"
android:layout_below="@+id/textView4"
android:text="@string/lJenisKelamin" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/lJk"
android:layout_below="@+id/lJk"
android:layout_marginTop="16dp"
android:text="@string/LTempatLahir" />
<TextView
android:id="@+id/lTTL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView6"
android:layout_below="@+id/textView6"
android:text="@string/LTempatLahir" />
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/lTTL"
android:layout_below="@+id/lTTL"
android:layout_marginTop="14dp"
android:text="@string/LStatusNikah" />
<TextView
android:id="@+id/lStatusNikah"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView7"
android:layout_below="@+id/textView7"
android:text="@string/LStatusNikah" />
<TextView
android:id="@+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/lStatusNikah"
android:layout_below="@+id/lStatusNikah"
android:layout_marginTop="16dp"
android:text="@string/LNoTelp" />
<TextView
android:id="@+id/lNoTelp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView8"
android:layout_below="@+id/textView8"
android:text="@string/LNoTelp" />
</RelativeLayout>
package com.example.sensusrt;import android.support.v7.app.ActionBarActivity;import android.support.v7.app.ActionBar;import android.support.v4.app.Fragment;import android.content.Intent;import android.database.Cursor;import android.database.SQLException;import android.os.Bundle;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.TextView;import android.widget.Toast;import android.os.Build;public class FormDetilActivity extends ActionBarActivity {static final private int EDIT_DATA = Menu.FIRST;static final private int DELETE_DATA = Menu.FIRST + 1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_form_detil);if (savedInstanceState == null) {getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.form_detil, menu);super.onCreateOptionsMenu(menu);// Create and add new menu items.MenuItem itemAdd = menu.add(0, EDIT_DATA, Menu.NONE,R.string.Edit);MenuItem itemRem = menu.add(0, DELETE_DATA, Menu.NONE,R.string.Hapus);// Assign iconsitemAdd.setIcon(R.drawable.edit);itemRem.setIcon(R.drawable.delete);// Allocate shortcuts to each of them.itemAdd.setShortcut('0', 'a');itemRem.setShortcut('1', 'r');return true;}@Overridepublic 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_settings) {return true;}else if(id==EDIT_DATA){Intent i = new Intent(this,FormPendataan.class);//startActivityForResult(SeninIntent, 0);//Toast.makeText(getActivity(), noKtp[1].toString(), Toast.LENGTH_LONG).show();String noKTP=functionSendiri.getExtraVariable("noKTP", this.getIntent());i.putExtra("noKTP", noKTP);startActivity(i);}else if(id==DELETE_DATA){Intent i = new Intent(this,FormDetilActivity.class);//startActivityForResult(SeninIntent, 0);//Toast.makeText(getActivity(), noKtp[1].toString(), Toast.LENGTH_LONG).show();DBAdapter db = new DBAdapter(this);String noKTP=functionSendiri.getExtraVariable("noKTP", this.getIntent());try {db.open();if(db.deletePenduduk(noKTP)==true){Toast.makeText(this, "Data berhasil dihapus", Toast.LENGTH_LONG).show();}else{Toast.makeText(this, "Data gagal dihapus", Toast.LENGTH_LONG).show();}db.close();} catch (SQLException e) {// TODO: handle exceptionToast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();}i.putExtra("noKTP", noKTP);startActivity(i);}return super.onOptionsItemSelected(item);}/*** A placeholder fragment containing a simple view.*/public static class PlaceholderFragment extends Fragment {public TextView tNoKTP, tNama, tJK, tTTL, tStatusNikah, tNoTelp;public PlaceholderFragment() {}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View rootView = inflater.inflate(R.layout.fragment_form_detil,container, false);tNoKTP = (TextView) rootView.findViewById(R.id.lNoKTP);tNama = (TextView) rootView.findViewById(R.id.lNama);tJK = (TextView) rootView.findViewById(R.id.lJk);tTTL = (TextView) rootView.findViewById(R.id.lTTL);tStatusNikah = (TextView) rootView.findViewById(R.id.lStatusNikah);tNoTelp = (TextView) rootView.findViewById(R.id.lNoTelp);String noKTP=functionSendiri.getExtraVariable("noKTP", getActivity().getIntent());tNoKTP.setText(noKTP);DBAdapter db = new DBAdapter(getActivity());try {db.open();Cursor c = db.getDataPenduduk(noKTP);tNoKTP.setText(c.getString(0));tNama.setText(c.getString(1));String Jk="";if(c.getString(2)=="L"){Jk="Laki-laki";}else{Jk="Perempuan";}tJK.setText(Jk);tTTL.setText(c.getString(3) +", "+c.getString(4));String statusNikah="";if(c.getString(5)=="M"){statusNikah="Menikah";}else{statusNikah="Lajang";}tStatusNikah.setText(statusNikah);tNoTelp.setText(c.getString(6));db.close();} catch (SQLException e) {// TODO: handle exceptionToast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();}return rootView;}}}
Di form detil ini, pengguna bisa merubah atau menghapus data penduduk. Klik tombol menu pada handphone kemudian pilih edit atau hapus data.
Aplikasi jadi bisa didownload di alamat berikut ini: