0% found this document useful (0 votes)
147 views

Crud Pada Eclipse Android Menggunakan Database Sqlite: Sourch Code Databaseapp - Java

The document discusses code for performing CRUD operations on an SQLite database in an Android Eclipse project using SQLite. It includes source code for a DatabaseApps class that allows users to load, add, update, and delete customer data from an SQLite database table using a list view. It also includes source code for a CustomerListAdapter class that extends BaseAdapter to populate and manage the list view contents from the customer data ArrayList.

Uploaded by

g1no_caem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
147 views

Crud Pada Eclipse Android Menggunakan Database Sqlite: Sourch Code Databaseapp - Java

The document discusses code for performing CRUD operations on an SQLite database in an Android Eclipse project using SQLite. It includes source code for a DatabaseApps class that allows users to load, add, update, and delete customer data from an SQLite database table using a list view. It also includes source code for a CustomerListAdapter class that extends BaseAdapter to populate and manage the list view contents from the customer data ArrayList.

Uploaded by

g1no_caem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Crud Pada Eclipse Android Menggunakan Database Sqlite

Sourch Code databaseapp.java :


package com.wilis.databaseapp;

import java.util.ArrayList;

import android.app.Activity;

import android.content.Intent;

import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.AdapterView;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ListView;

import android.widget.TextView;

import android.widget.Toast;

import android.widget.AdapterView.OnItemClickListener;

import android.widget.AdapterView.OnItemLongClickListener;

public class DatabaseApps extends Activity {

ArrayList<Customer> currentData;

SQLiteDatabase database;

CustomerListAdapter adapter;
ListView list;

CustomerSQLHelper helper;

Customer cust;

Button btnSubmit, btnCancel;

TextView txtTitle;

EditText dtName, dtAddress, dtPhone;

Utils util;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.listview);

util = new Utils(this);

list = (ListView) findViewById(R.id.list_data);

CustomerSQLHelper helper = new CustomerSQLHelper(this);

database = helper.getWritableDatabase();

currentData = new ArrayList<Customer>();

// ---- load data ----

currentData = util.loadData();
adapter = new CustomerListAdapter(this, currentData);

list.setAdapter(adapter);

list.setEmptyView(findViewById(R.id.list_empty));

list.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View v,

int position, long id) {

adapter.toggleDataCompleteAtPosition(position);

});

list.setOnItemLongClickListener(new OnItemLongClickListener() {

public boolean onItemLongClick(AdapterView<?> parent, View v,

int position, long id) {

Customer c = adapter.getItem(position);

util.onShowData(c, DatabaseApps.this);

return false;

});

// set button click


onButtonClick();

// ----------------------------------------------

@Override

protected void onResume() {

super.onResume();

adapter.forceReload();

// -----------------------------------------------

public void onButtonClick() {

Button btnAdd = (Button) findViewById(R.id.add_button);

btnAdd.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

onCreateWidgetData(1, new Customer()); }

});

Button btnUpdate = (Button) findViewById(R.id.update_button);

btnUpdate.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

Customer c = adapter.getCheckedCustomer();

if (!c.getName().equals(""))

onCreateWidgetData(2, c);

else {
Toast.makeText(DatabaseApps.this, "Harus centang satu",

Toast.LENGTH_LONG).show();

});

Button btnDelete = (Button) findViewById(R.id.delete_button);

btnDelete.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

Customer c = adapter.getCheckedCustomer();

onDeleteData(c.getId());

});

Button btnExit = (Button) findViewById(R.id.exit_button);

btnExit.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

finish();

android.os.Process.killProcess(android.os.Process.myPid());

});

public void onCreateWidgetData(int param, final Customer getCust) {


switch(param) {

// add data new

case 1:

widgetAdd();

break;

// update existing data

case 2:

widgetUpdate(getCust);

break;

public void widgetAdd() {

setContentView(R.layout.inputdata);

txtTitle = (TextView) findViewById(R.id.txt_title);

txtTitle.setText("Add Data");

btnSubmit = (Button) findViewById(R.id.submit_button);

btnSubmit.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

dtName = (EditText) findViewById(R.id.data_name);

dtAddress = (EditText) findViewById(R.id.data_address);

dtPhone = (EditText) findViewById(R.id.data_phone);


if (dtName.getText().length()<1

|| dtAddress.getText().length()<1

|| dtPhone.getText().length()<1) {

Toast.makeText(DatabaseApps.this, "Check your input...",

Toast.LENGTH_SHORT).show();

else {

cust = new Customer();

cust.setName(dtName.getText().toString());

cust.setAddress(dtAddress.getText().toString());

cust.setPhone(dtPhone.getText().toString());

cust.setComplete(false);

util.onSaveData(cust);

onCancel();

});

btnCancel = (Button) findViewById(R.id.cancel_button);

btnCancel.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

onCancel();

});

}
public void widgetUpdate(final Customer getCust) {

setContentView(R.layout.inputdata);

txtTitle = (TextView) findViewById(R.id.txt_title);

txtTitle.setText("Update Data");

dtName = (EditText) findViewById(R.id.data_name);

dtName.setText(getCust.getName());

dtAddress = (EditText) findViewById(R.id.data_address);

dtAddress.setText(getCust.getAddress());

dtPhone = (EditText) findViewById(R.id.data_phone);

dtPhone.setText(getCust.getPhone());

btnSubmit = (Button) findViewById(R.id.submit_button);

btnSubmit.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

dtName = (EditText) findViewById(R.id.data_name);

dtAddress = (EditText) findViewById(R.id.data_address);

dtPhone = (EditText) findViewById(R.id.data_phone);

if (dtName.getText().length()<1

|| dtAddress.getText().length()<1
|| dtPhone.getText().length()<1) {

Toast.makeText(DatabaseApps.this, "Check your input...",


Toast.LENGTH_SHORT);

else {

getCust.setName(dtName.getText().toString());

getCust.setAddress(dtAddress.getText().toString());

getCust.setPhone(dtPhone.getText().toString());

util.onUpdateData(getCust); onCancel();

});

btnCancel = (Button) findViewById(R.id.cancel_button);

btnCancel.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

onCancel();

});

public void onDeleteData(long id) {

// Long[] ids = adapter.removeCheckedCustomer();

// deleteData(ids);

deleteData(new Long[]{id});
currentData = util.loadData();

adapter = new CustomerListAdapter(this, currentData);

list.setAdapter(adapter);

@SuppressWarnings("static-access")

public void deleteData(Long[] ids) {

StringBuffer idList = new StringBuffer();

for (int i =0; i< ids.length; i++) {

idList.append(ids[i]);

if (i < ids.length -1 ) {

idList.append(",");

String where = String.format("%s in (%s)", helper.TASK_ID, idList);

database.delete(helper.TASKS_TABLE, where, null);

public void onCancel() {

Intent newIntent = new Intent().setClass(DatabaseApps.this,

DatabaseApps.class);

startActivity(newIntent);

finish();

}
// -----------------------------------------------

Sourch Code CustomerListAdapter.java :

package com.wilis.databaseapp;

import java.util.ArrayList;

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.CheckedTextView;

import android.widget.TextView;

public class CustomerListAdapter extends BaseAdapter {

ArrayList<Customer> cust;

Context context;

public CustomerListAdapter(Context context, ArrayList<Customer> custs) {

super();

this.cust = custs;

this.context = context;

}
@Override

public int getCount() {

return cust.size();

@Override

public Customer getItem(int position) {

return (null == cust) ? null : cust.get(position);

@Override

public long getItemId(int position) {

return position;

public static class ViewHolder {

public CheckedTextView nameView;

public TextView idView;

@Override

public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder holder;
View vi = convertView;

if (null == convertView) {

LayoutInflater infalInflater = (LayoutInflater) context

.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

vi = infalInflater.inflate(R.layout.listitem, null);

holder = new ViewHolder();

holder.nameView = (CheckedTextView)vi.findViewById(R.id.txt_name);

holder.idView = (TextView) vi.findViewById(R.id.txt_id);

vi.setTag(holder);

else

holder = (ViewHolder) vi.getTag();

String txtName = cust.get(position).getName()+"-


"+cust.get(position).getAddress();

String txtId = String.valueOf(cust.get(position).getId());

boolean check = cust.get(position).isComplete();

holder.nameView.setText(txtName);

holder.nameView.setChecked(check);

holder.idView.setText(txtId);

return vi;

}
public void forceReload() {

notifyDataSetChanged();

public void toggleDataCompleteAtPosition(int position) {

Customer cust = getItem(position);

cust.toggleComplete();

notifyDataSetChanged();

public Long[] removeCheckedCustomer() {

ArrayList<Customer> completedTasks = new ArrayList<Customer>();

ArrayList<Long> completedIds = new ArrayList<Long>();

for (Customer dtCust : cust) {

if (dtCust.isComplete()) {

completedTasks.add(dtCust);

completedIds.add(dtCust.getId());

cust.removeAll(completedTasks);

notifyDataSetChanged();

return completedIds.toArray(new Long[]{});

public Customer getCheckedCustomer() {

Customer newCust = new Customer();


for (Customer dtCust : cust) {

if (dtCust.isComplete()) {

newCust = dtCust; break;

return newCust;

Sourch Code Customer.java :


package com.wilis.databaseapp;

import java.util.ArrayList;

import android.app.AlertDialog;

import android.content.ContentValues;

import android.content.Context;

import android.content.DialogInterface;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

public class Utils {

CustomerSQLHelper helper;

SQLiteDatabase database;
public Utils(Context ctx) {

helper = new CustomerSQLHelper(ctx);

database = helper.getWritableDatabase();

@SuppressWarnings("static-access")

public ArrayList<Customer> loadData() {

ArrayList<Customer> currentData = new ArrayList<Customer>();

Cursor dataCursor = database.query(helper.TASKS_TABLE,

new String[] {helper.TASK_ID, helper.TASK_NAME,

helper.TASK_ADDRESS,

helper.TASK_PHONE, helper.TASK_COMPLETE},

null, null, null, null,

String.format("%s, %s", helper.TASK_COMPLETE,


helper.TASK_NAME));

dataCursor.moveToFirst();

Customer t;

if ( !dataCursor.isAfterLast() ) {

do {

int id = dataCursor.getInt(0); // coloum ID

String name = dataCursor.getString(1); // coloum name

String addr = dataCursor.getString(2); // coloum address

String phon = dataCursor.getString(3); // coloum phone


String boolValue = dataCursor.getString(4); // coloum complete

boolean complete = Boolean.parseBoolean(boolValue);

t = new Customer();

t.setId(id);

t.setName(name);

t.setAddress(addr);

t.setPhone(phon);

t.setComplete(complete);

currentData.add(t);

} while(dataCursor.moveToNext());

/*

while (dataCursor.moveToNext()) {

*/

dataCursor.close();

return currentData;

}
@SuppressWarnings("static-access")

public void onSaveData(Customer getCust) {

assert (null != getCust);

ContentValues values = new ContentValues();

values.put(helper.TASK_NAME, getCust.getName());

values.put(helper.TASK_ADDRESS, getCust.getAddress());

values.put(helper.TASK_PHONE, getCust.getPhone());

values.put(helper.TASK_COMPLETE, Boolean.toString(false));

getCust.setId(database.insert(helper.TASKS_TABLE, null, values));

@SuppressWarnings("static-access")

public void onUpdateData(Customer getCust) {

assert (null != getCust);

ContentValues values = new ContentValues();

values.put(helper.TASK_NAME, getCust.getName());

values.put(helper.TASK_ADDRESS, getCust.getAddress());

values.put(helper.TASK_PHONE, getCust.getPhone());

values.put(helper.TASK_COMPLETE, Boolean.toString(getCust.isComplete()));

long id = getCust.getId();

String where = String.format("%s = %d", helper.TASK_ID, id);


database.update(helper.TASKS_TABLE, values, where, null);

AlertDialog alert;

public void onShowData(Customer cust, Context ctx) {

final Customer thisCust = cust;

alert = new AlertDialog.Builder(ctx).setIcon(R.drawable.icon)

.setTitle("Display Data")

.setMessage(" ------------ Customer -------------\n"

+ "ID: "+thisCust.getId()+"\n"

+ "Name: "+thisCust.getName()+"\n"

+ "Adress: "+thisCust.getAddress()+"\n"

+ "Phone: "+thisCust.getPhone()+"\n")

.setNegativeButton("Close", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int whichButton) {

alert.cancel();

}).create();

alert.show();

Sourch Code inputdata.xml :


<?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:layout_height="match_parent">
<TextView android:id="@+id/txt_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:textSize="20px"
android:text="title" />

<EditText
android:id="@+id/data_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Isikan Nama Anda" />

<EditText
android:id="@+id/data_address"
android:layout_width="fill_parent"
android:layout_height="100px"
android:gravity="top"
android:hint="Alamat Anda"
android:singleLine="false" />

<EditText
android:id="@+id/data_phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Nomor Telpon"
android:phoneNumber="true" />

<Button
android:id="@+id/submit_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Kirim" />

<Button
android:id="@+id/cancel_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Kembali" />

</LinearLayout>

Sourch Code listview.xml :


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="@+id/list_data"
android:layout_width="fill_parent"
android:layout_above="@+id/add_button"
android:layout_height="fill_parent" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/list_empty"
android:text="no data"
android:gravity="center_vertical|center_horizontal"
android:layout_above="@+id/add_button" />

<Button
android:id="@+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="35px"
android:text="Tambah" />

<Button
android:id="@+id/update_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@id/add_button"
android:text="Edit" />

<Button
android:id="@+id/delete_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@id/update_button"
android:text="Hapus" />

<Button
android:id="@+id/exit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@id/delete_button"
android:text="Keluar" />

</RelativeLayout>

Sourch Code listitem.xml :


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:padding="5px" >

<CheckedTextView android:id="@+id/txt_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="Name Customer"
android:checkMark="?android:attr/listChoiceIndicatorMultiple" />

<TextView android:id="@+id/txt_id"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:visibility="gone" />

</LinearLayout>

Hasil Running :

Tampilan Awal Aplikasi

Tambah Data, klik tombol button Tambah


Data berhasil di tambahkan :

You might also like