Tugas 3 | Membuat CRUD

Buatlah project baru seperti ketentuan berikut :

Project Name : DatabaseApps
Buitl Target : Android 2.2
Application name : DatabaseApps
Package name : com.wilis.databaseapp
Activity : DatabaseApps
Min SDK :8

Pada Package Explorer, Buka file main.xml di folder res/layout, perhatikan gambar berikut 








Ganti Kode pada main.xml menjadi sepertik berikut

main.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">
    
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello" />
        
</LinearLayout>



-----------------------------------------------------------------------------------
Buatlah xml baru, klik kanan pada layout -> New -> Android XML File beri nama inputdata.xml
Ganti Kode pada inputdata.xml menjadi sepertik berikut :

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="Your name"/>
    <EditText android:id="@+id/data_address" android:layout_width="fill_parent"
        android:layout_height="100px" android:hint="Your address"
        android:gravity="top" android:singleLine="false"/>    
    <EditText android:id="@+id/data_phone" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:phoneNumber="true"
        android:hint="Your phone" />
            
    <Button android:id="@+id/submit_button" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="submit" />
    <Button android:id="@+id/cancel_button" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="cancel" />
</LinearLayout>
-----------------------------------------------------

Buatlah xml baru, klik kanan pada layout -> New -> Android XML File beri nama listitem.xml
Ganti Kode pada listitem.xml menjadi sepertik berikut :

listitem.xm
--------------------------------------------------------------------------------------------------------------------
<?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>



-----------------------------------------------------------------------------------
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:text="Add" android:layout_marginLeft="35px"/>        
    <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="Update" />
    <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="Delete" />
    <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="Exit"/>        
</RelativeLayout>
---------------------------------------------------------

login.xml

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


---------------------------------------------
Disini Saya menggunakan 6 class



Berikut Sourcode Classnya.  
Customer.java 

--------------------------------------------------------------------------
package com.wilis.databaseapp;

public class Customer {

    long id;
    String name;
    String address;
    String phone;
    boolean complete;
    
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public boolean isComplete() {
        return complete;
    }
    public void setComplete(boolean complete) {
        this.complete = complete;
    }
    
    // -------------------------------------------
    public void toggleComplete() {
        complete = !complete;
    }    
    
}


-----------------------------------------


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;
    }
}


---------------------------------
CustomerSQLHelper.java

------------------------------------------------

package com.wilis.databaseapp;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class CustomerSQLHelper extends SQLiteOpenHelper {

    public static final String DB_NAME = "customer_db.sqllite";
    public static final int VERSION = 1;
    
    public static final String TASKS_TABLE = "customer";
    public static final String TASK_ID = "id";
    public static final String TASK_NAME = "name";
    public static final String TASK_ADDRESS = "address";
    public static final String TASK_PHONE   = "phone";
    public static final String TASK_COMPLETE = "complete";
    
    public CustomerSQLHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        createTable(db);
    }

    private void createTable(SQLiteDatabase db) {
        db.execSQL("create table " + TASKS_TABLE + " ( " + 
        TASK_ID + " integer primary key autoincrement not null, " +
        TASK_NAME + " text, " + 
        TASK_ADDRESS + " text, " +
        TASK_PHONE + " text, " +
        TASK_COMPLETE + " text " +
        ");"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

---------------------------------------------------------------------

DatabaseApps .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();
    }
    
    // -----------------------------------------------
}


-----------------------------------------

NewActivity.java

-----------------------------------------------------------------------------------------------------------------

package com.wilis.databaseapp;

import android.app.Activity;
import android.os.Bundle;

public class NewActivity extends Activity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inputdata);
        
        
    }
    
}


----------------------------------
NewForm.java

--------------------------------------------------------------

package com.wilis.databaseapp;

import android.app.Activity;
import android.os.Bundle;

public class NewForm extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

    }

}

----------------------------------------

Utils.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();
    }
}

-----------------------------------------------------


Untuk Mengatasi Terjadinya Force Close, Pada package src/AndroidManifest, buka AndroidManifest.xml pastikan kodenya seperti berikut




Setelah itu Kita Jalankan Aplikasinya.

Share this

Related Posts

Previous
Next Post »