Senin, 07 Januari 2013

Aplikasi Android Menambah Data, Insert Database SQLite

Setelah selesai Membuat Aplikasi Android untuk Menampilkan Data dari Database SQLite di Android, kita lanjutkan bagian berikutnya yaitu Menambahkan Data ke Database SQLite di Android. Silakan download atau ikuti pembuatan program dari Artikel sebelumnya untuk kemudian kita tambahkan kemampuan Android Menambah Data di Database SQLite

Pertama kita modifikasi dahulu class Main Activity agar bisa memanggil AddActivity :
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);
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 program utama untuk menambah data kita buat Activity baru bernama AddActivity.java :

AddActivity.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 AddActivity extends Activity {
protected Cursor cursor;
SQLHelper dbHelper;

Button btnAddSimpan;
EditText edAddNama;
EditText edAddLatitude;
EditText edAddLongitude;
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add);
        
        dbHelper = new SQLHelper(this);
        
        edAddNama = (EditText) findViewById(R.id.edAddNama);
        edAddLatitude = (EditText) findViewById(R.id.edAddLatitude);
        edAddLongitude = (EditText) findViewById(R.id.edAddLongitude);
        
        btnAddSimpan = (Button) findViewById(R.id.btnAddSimpan);
// daftarkan even onClick pada btnSimpan
    btnAddSimpan.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.execSQL("insert into kota(nama, latitude, longitude) values('" + edAddNama.getText().toString()+
"','"+ edAddLatitude.getText().toString() +"','" + edAddLongitude.getText().toString() + "')");
Toast.makeText(getApplicationContext(), "Berhasil", Toast.LENGTH_LONG).show();
MainActivity.ma.RefreshList();
finish();
}

});

    }
}

Kemudian tampilannya AddActivity yaitu add.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 :

add.xml

<?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/edAddNama" 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/edAddLatitude" 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/edAddLongitude" android:layout_width="100dp" android:layout_height="wrap_content"></EditText>
<Button android:text="Simpan" android:id="@+id/btnAddSimpan" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

Pada AndroidManifest.xml perlu ditambah untuk mendeklarasikan AddActivity tidak perlu diubah :

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 Mengupdate / Edit Data pada Database SQLite