Selasa, 08 Januari 2013

Aplikasi Android Mengedit Data, Update Database SQLite

Tulisan ini adalah sambungan dari artikel sebelumnya yaitu Membuat Aplikasi Android untuk Menambah Data ke Database SQLite. Silakan download atau ikuti pembuatan program dari Artikel tersebut untuk kemudian kita tambahkan kemampuan Android Mengupdate / Edit Data di Web Database SQLite.

Pada Program utama di MainActivity kita tambahkan beberapa baris program untuk memanggil Activity baru yang berfungsi untuk mengedit / update Data yaitu EditActivity :

MainActivity.java

package com.amijaya.databasesqlite;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

// http://cariprogram.blogspot.com
// nuramijaya@gmail.com

public class MainActivity extends Activity {
String[] daftar; // = {"Wisata Candi", "Wisata Pantai", "Wisata Alam"};
ListView ListView01;
Menu menu;
protected Cursor cursor;
SQLHelper dbHelper;
public static MainActivity ma;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ma = this;
        
        dbHelper = new SQLHelper(this);

RefreshList();
    }
    
    public void RefreshList()
    {
    SQLiteDatabase db = dbHelper.getReadableDatabase();

cursor = db.rawQuery("SELECT * FROM kota",null);

daftar = new String[cursor.getCount()];
cursor.moveToFirst();
for (int cc=0; cc < cursor.getCount(); cc++)
{
cursor.moveToPosition(cc);
daftar[cc] = cursor.getString(1).toString();
}

    ListView01 = (ListView)findViewById(R.id.ListView01);
        ListView01.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, daftar));
        ListView01.setSelected(true);
        ListView01.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
final String selection = daftar[arg2]; //.getItemAtPosition(arg2).toString();
    final CharSequence[] dialogitem = {"Edit", "Delete"};
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
       builder.setTitle("Pilih ?");
       builder.setItems(dialogitem, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item){
case 0 :
Intent i = new Intent(getApplicationContext(), EditActivity.class); //KulineryogyaActivity.class); 
i.putExtra("nama", selection);
    startActivity(i);

break;
case 1 :
/*SQLiteDatabase db = dbHelper.getWritableDatabase();
db.execSQL("delete from kota where nama = '"+selection+"'");
       RefreshList();*/
break;
}
}
});
       builder.create().show();
}});

        
        ((ArrayAdapter)ListView01.getAdapter()).notifyDataSetInvalidated();   
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    this.menu = menu;
   
    menu.add(0, 1, 0, "Tambah").setIcon(android.R.drawable.btn_plus);
    menu.add(0, 2, 0, "Refresh").setIcon(android.R.drawable.ic_menu_rotate);
        menu.add(0, 3, 0, "Exit").setIcon(android.R.drawable.ic_menu_close_clear_cancel);
    return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 1:
        Intent i = new Intent(MainActivity.this, AddActivity.class);
        startActivity(i);
            return true;
        case 2:            
            RefreshList();         
    return true;
        case 3:
            finish();
            return true;
        }
    return false;
    }

}

Kemudian kita buat Activity baru yaitu EditActivity.java :

EditActivity.java :

package com.amijaya.databasesqlite;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

//http://cariprogram.blogspot.com
//nuramijaya@gmail.com

public class EditActivity extends Activity {
protected Cursor cursor;
SQLHelper dbHelper;

Button btnEditSimpan;
EditText edEditNama;
EditText edEditLatitude;
EditText edEditLongitude;
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit);
        
        dbHelper = new SQLHelper(this);
        
        edEditNama = (EditText) findViewById(R.id.edEditNama);
        edEditLatitude = (EditText) findViewById(R.id.edEditLatitude);
        edEditLongitude = (EditText) findViewById(R.id.edEditLongitude);
        
        SQLiteDatabase db = dbHelper.getReadableDatabase();

cursor = db.rawQuery("SELECT * FROM kota WHERE nama = '" + getIntent().getStringExtra("nama") + "'",null);

cursor.moveToFirst();
if (cursor.getCount()>0)
{
cursor.moveToPosition(0);
edEditNama.setText(cursor.getString(1).toString());
edEditLatitude.setText(cursor.getString(2).toString());
edEditLongitude.setText(cursor.getString(3).toString());
}
        
        btnEditSimpan = (Button) findViewById(R.id.btnEditSimpan);
// daftarkan even onClick pada btnSimpan
        btnEditSimpan.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.execSQL("update kota SET nama='" + edEditNama.getText().toString()+"', " +
"latitude='"+ edEditLatitude.getText().toString() +"', " +
"longitude='" + edEditLongitude.getText().toString() + "' WHERE " +
   " nama = '" + getIntent().getStringExtra("nama") + "'");
Toast.makeText(getApplicationContext(), "Berhasil", Toast.LENGTH_LONG).show();
MainActivity.ma.RefreshList();
finish();
}

});

    }
}

Kemudian tampilannya EditActivity yaitu edit.xml kita pakai saja tampilan default kemudian ditambah tiga buah TextView, kemudian tiga buah EditText dengan nama edAddNama, edAddLatitude, edAddLongitude, Kemudian tambahkan satu buah Button dengan Nama btnAddSimpan :

edit.xml

<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical">
<TextView android:text="Nama" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:id="@+id/edEditNama" android:layout_width="100dp" android:layout_height="wrap_content"></EditText>
<TextView android:text="Latitude" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:id="@+id/edEditLatitude" android:layout_width="100dp" android:layout_height="wrap_content"></EditText>
<TextView android:text="Longitude" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:text="" android:id="@+id/edEditLongitude" android:layout_width="100dp" android:layout_height="wrap_content"></EditText>
<Button android:text="Simpan" android:id="@+id/btnEditSimpan" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

Pada AndroidManifest.xml kita tambahkan deklarasi untuk menampilkan activity EditActivity:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.amijaya.databasesqlite"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".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=".AddActivity"
                  android:label="@string/app_name">
        </activity>
        <activity android:name=".EditActivity"
                  android:label="@string/app_name">
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="8" />

</manifest> 

Hasilnya




Project selengkapnya silakan didownload disini :
https://docs.google.com/open?id=0B4i1FYc_4RXzRk04d0NhQlE4OGs

Semoga bermanfaat, Selamat Coding.

Artikel Selanjutnya Aplikasi Android untuk Menghapus Data pada Database SQLite