Eclipse SQLite Implementation (ESI)


ESI:   SOLD       




SQLite is a database that can be built on Android. SQLite has relational database features, almost the same as SQL on the desktop except that SQLite requires a little memory.


Android SQLite Database Implementation in Eclipse PART 1

SQLite is available on all android devices, you simply define SQL commands to create or update a database, then the android system will handle things related to the database. SQLite databases will automatically be stored in the path data/data/package_name/database/database_name.

Before starting to create a SQLite database application, there are 3 classes that you should know, namely;

1. SQLite Database

SQLiteDatabase is a class that has methods such as

  • Insert() to add rows to the database
  • Update() to update rows in the database 
  • Delete() to delete rows in the database 
  • execSQL() to execute SQL syntax

2. SQLiteOpenHelper

SQLiteOpenHelper is a subclass that has several methods such as

  • onCreate() is executed if there is no database yet
  • onUpgrade() is executed if the same database has been found but a different version. This method can be used to change the database schema. 
  • onOpen() is executed if the database is already open 
  • getWritableDatabase() calls the database to allow data to be entered. 
  • getReadableDatabase() calls the database to read its data.

3. Cursor

Every executed query must bring a return value or feedback. The feedback generated by this query is called a cursor. So in other words, a cursor represents the results of a query executed on a particular row and column. Figure 12.1 below will help you understand the term cursor in SQLite.


Figure 12.1. Analogy of cursor in SQLite database

The cursor is represented by the arrow located in the 2nd row position carrying the data [fitri,masak]. Here are some methods used in this exercise;

  • moveToFirst() to move to the first row
  • isAfterLast() will send a return message if the cursor position is already on the last line. 
  • getLong() to retrieve data in columns that have the long data type 
  • getString() to retrieve data in columns that have the String data type

4. Creating an Android Database in Eclipse

Before starting to create a project, it's a good idea to first look at the final result of the Android Database project #1 in figure 12.2.

We will create a database of someone's hobbies. Data is entered through 2 edittexts, then the add button is used to save data into the database and update the table if the data is successfully saved.


Figure 12.2 Android database #1

Are you ready?? Let's practice

1. Prepare a new project with the following name

| Project name    | DatabaseAndroid     |
|-----------------|---------------------|
| Build Target    | Android 2.2         |
| Aplication name | Database Android #1 |
| Package name    | Com.db.satu         |
| Create Activity | DatabaseAndroidSatu |
| Min SDK version | 8                   |

2. Change the String.xml section as follows

<?xml version="1.0" encoding="utf-8"?>
 <resources>
 <string name="hello">Masukkan nama dan hobi</string>
 <string name="app_name">Database Android #1</string>
 <string name="btnAddtxt">Add</string>
 <string name="namaLabel">Nama</string>
 <string name="hobiLabel">hobi</string>
 <string name="nomorLabel">No.</string>
</resources>

3. Change main.xml as follows

<?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 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:id="@+id/linearLayout1">
 <EditText android:id="@+id/inNama"
 android:layout_height="wrap_content"
 android:layout_width="100dip"></EditText>
 <EditText android:id="@+id/inHobi"
 android:layout_height="wrap_content"
 android:layout_width="100dip"></EditText>
 <Button android:layout_width="wrap_content"
 android:id="@+id/btnAdd"
 android:layout_height="wrap_content"
 android:text="@string/btnAddtxt"></Button>
 </LinearLayout>
 <TableLayout android:layout_height="wrap_content"
 android:layout_width="match_parent"
 android:id="@+id/tabel_data">
 <TableRow android:id="@+id/tableRow1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content">
 <TextView android:layout_height="wrap_content"
 android:layout_width="50dip"
 android:text="@string/nomorLabel"
 android:id="@+id/no_id"></TextView>
 <TextView android:layout_height="wrap_content"
 android:layout_width="100dip"
 android:text="@string/namaLabel"
 android:id="@+id/nama_id"></TextView>
 <TextView android:layout_width="100dip"
 android:layout_height="wrap_content"
 android:text="@string/hobiLabel"
 android:id="@+id/hobi_id"></TextView>
 </TableRow>
 </TableLayout>
</LinearLayout>

4. Create a new class then name it DatabaseManager.java, then type the following line of code.

package com.db.satu;

 import java.util.ArrayList;

 import android.content.ContentValues;
 import android.content.Context;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.util.Log;

 public class DatabaseManager {

 private static final String ROW_ID = "_id";
 private static final String ROW_NAMA = "nama";
 private static final String ROW_HOBI = "hobi";

 private static final String NAMA_DB = "DatabaseAndroidSatu";
 private static final String NAMA_TABEL = "hobiku";
 private static final int DB_VERSION = 1;

 private static final String CREATE_TABLE = "create table "+NAMA_TABEL+" ("+ROW_ID+" integer PRIMARY KEY autoincrement, "+ROW_NAMA+" text,"+ROW_HOBI+" text)";

 private final Context context;
 private DatabaseOpenHelper dbHelper;
 private SQLiteDatabase db;

 public DatabaseManager(Context ctx) {
 this.context = ctx;
 dbHelper = new DatabaseOpenHelper(context);
 db = dbHelper.getWritableDatabase();
 }

 private static class DatabaseOpenHelper extends SQLiteOpenHelper {

 public DatabaseOpenHelper(Context context) {
 super(context, NAMA_DB, null, DB_VERSION);
 // TODO Auto-generated constructor stub
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
 // TODO Auto-generated method stub
 db.execSQL(CREATE_TABLE);
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) {
 // TODO Auto-generated method stub
 db.execSQL("DROP TABLE IF EXISTS "+NAMA_DB);
 onCreate(db);

 }
 }
 public void close() {
 dbHelper.close();
 }

 public void addRow(String nama, String hobi) {
 ContentValues values = new ContentValues();
 values.put(ROW_NAMA, nama);
 values.put(ROW_HOBI, hobi);
 try {
 db.insert(NAMA_TABEL, null, values);
 } catch (Exception e) {
 Log.e("DB ERROR", e.toString());
 e.printStackTrace();
 }
 }

 public ArrayList<ArrayList<Object>> ambilSemuaBaris() {
 ArrayList<ArrayList<Object>> dataArray = new ArrayList<ArrayList<Object>>();
 Cursor cur;
 try {
 cur = db.query(NAMA_TABEL,
 new String[] { ROW_ID, ROW_NAMA, ROW_HOBI }, null, null,
 null, null, null);
 cur.moveToFirst();
(!cur.isAfterLast()) {
 do {
 ArrayList<Object> dataList = new ArrayList<Object>();
 dataList.add(cur.getLong(0));
 dataList.add(cur.getString(1));
 dataList.add(cur.getString(2));
 dataArray.add(dataList);
 } while (cur.moveToNext());
 }
 } catch (Exception e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 Log.e("DEBE ERROR", e.toString());
 }
 return dataArray;
 }
}

5. Now we add code to the DatabaseAndroidSatu.java activity as below.

package com.db.satu;

 import java.util.ArrayList;
 import android.app.Activity;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.TableLayout;
 import android.widget.TableRow;
 import android.widget.TextView;
 import android.widget.Toast;

 public class DatabaseAndroidSatu extends Activity {
 DatabaseManager dm;
 EditText nama, hobi;
 Button addBtn;
 TableLayout tabel4data;// tabel for data

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

 dm = new DatabaseManager(this);
 tabel4data = (TableLayout) findViewById(R.id.tabel_data);
 nama = (EditText) findViewById(R.id.inNama);
 hobi = (EditText) findViewById(R.id.inHobi);
 addBtn = (Button) findViewById(R.id.btnAdd);
 addBtn.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 simpKamuta();
 }

 });
 updateTable();
 }

 protected void simpKamuta() {
 try {
 dm.addRow(nama.getText().toString(),hobi.getText().toString());
 Toast.makeText(getBaseContext(),
 nama.getText().toString() + ", berhasil disimpan",
 Toast.LENGTH_SHORT).show();
 updateTable();
 kosongkanField();
 } catch (Exception e) {
 e.printStackTrace();
 Toast.makeText(getBaseContext(), "gagal simpan, " + e.toString(),Toast.LENGTH_LONG).show();
 }
 }
 protected void kosongkanField(){
 nama.setText("");
 hobi.setText("");
 }
 protected void updateTable() {
 // TODO Auto-generated method stub
 while (tabel4data.getChildCount() > 1) {
 tabel4data.removeViewAt(1);
 }

 ArrayList<ArrayList<Object>> data = dm.ambilSemuaBaris();//

 for (int posisi = 0; posisi < data.size(); posisi++) {
 TableRow tabelBaris = new TableRow(this);
 ArrayList<Object> baris = data.get(posisi);

 TextView idTxt = new TextView(this);
 idTxt.setText(baris.get(0).toString());
 tabelBaris.addView(idTxt);

 TextView namaTxt = new TextView(this);
 namaTxt.setText(baris.get(1).toString());
 tabelBaris.addView(namaTxt);

 TextView hobiTxt = new TextView(this);
 hobiTxt.setText(baris.get(2).toString());
 tabelBaris.addView(hobiTxt);

 tabel4data.addView(tabelBaris);
 }
 }
}

If there are no errors, then the AndroidDatabaseSatu application is ready to run.

Program Explanation

In the database project we have the DatabaseManager.java java class (not an activity). This class consists of;

  • Declaring variables on lines 14-26
  • DatabaseManager constructor on lines 28-32
  • subClass DatabaseOpenHelper on lines 34-54
  • Close method on lines 55-57
  • Method addRow on lines 59-69
  • GetAllRows method on lines 71-94

In the DatabaseManager constructor, we define a DatabaseOpenHelper subclass and put the getWritableDatabase method so that when this project is run, the database is immediately set to be writable.

The DatabaseOpenHelper subclass also has a DatabaseOpenHelper controctor which contains the super() method. This method is called to identify the name and version of the database. This subclass also contains the onCreate() method to generate a database if there was no similar database previously and also the onUpdate() method which will be executed if a database with a newer version is found.

The addRow method is responsible for adding data to the database. Inside it is the ContentValues() class, used to store a pair of data. The put(ROW_NAME, name) row means adding data carried by the name variable to the name column. The takeAllRows method is used to read the entire contents of the database. The data that is read is then stored in a nested array. The output of this method is data [_id, name, hobby].

Next we discuss the listing in the AndroidDatabaseSatu.java activity. This activity has 4 methods, namely onCreate(), simpKamuta(), updateTable(), kosongkanField(). All methods begin with void because they do not have any return value.

In the simpKamuta() method, we use the addRow() method of the DatabaseManager class to add data to the database. While in the updateTable() method, we call the fetchAllRows() method to display data to the table. The emptyField() method is used to empty the edittext again.

In this section, you will learn about:

  1. Update
  2. Delete

Now let's develop our understanding of the database by adding some features such as changing data and deleting data that previously existed in the database. First, take a look at Figure 12.3 below;


Figure 12.3

1. Create a new project with the following parameters

| Project name    | DatabaseAndroid     |
|-----------------|---------------------|
| Build Target    | Android 2.2         |
| Aplication name | Database Android #2 |
| Package name    | Com.db.dua          |
| Create Activity | DatabaseAndroidDua  |
| Min SDK version | 8                   |

2. Change Strings.xml as follows

<?xml version="1.0" encoding="utf-8"?>
 <resources>
 <string name="hello">Masukkan nama dan hobi</string>
 <string name="app_name">Database Android #2</string>
 <string name="btnAddtxt">Add</string>
 <string name="namaLabel">Nama</string>
 <string name="hobiLabel">hobi</string>
 <string name="nomorLabel">No.</string>
 <string name="btnGetRow">Get</string>
 <string name="btnUpdateRow">Update</string>
 <string name="ketUpdate">Sebelum mengubah data, pilih dulu baris ke berapa data yang akan diubah</string>
 <string name="ketAmbilBaris">Update data pada bariske</string>
 <string name="ketDelete">Tulis no. baris yang akan di delete, lalu klik tombol &quot;delete&quot;</string>
 <string name="btnDel">Delete</string>
 </resources>

3. Create a Main.xml layout like this

<?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 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:id="@+id/linearLayout1">
 <EditText android:id="@+id/inNama"
 android:layout_height="wrap_content"
 android:layout_width="100dip"></EditText>
 <EditText android:id="@+id/inHobi"
 android:layout_height="wrap_content"
 android:layout_width="100dip"></EditText>
 <Button android:layout_width="wrap_content"
 android:id="@+id/btnAdd"
 android:layout_height="wrap_content"
 android:text="@string/btnAddtxt"></Button>
 </LinearLayout>
 <View android:layout_width="wrap_content"
 android:id="@+id/view2"
 android:layout_height="1dip"
 android:background="#FF909090"></View>
 <TextView android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:id="@+id/textView1"
 android:text="@string/ketUpdate"></TextView>
 <View android:layout_width="wrap_content"
 android:id="@+id/view2"
 android:layout_height="1dip"
 android:background="#FF909090"></View>
 <LinearLayout android:layout_width="match_parent"
 android:id="@+id/linearLayout2"
 android:layout_height="wrap_content">
 <TextView android:layout_width="wrap_content"
 android:text="@string/ketAmbilBaris"
 android:layout_height="wrap_content"
 android:id="@+id/textView2"></TextView>
 <EditText android:layout_height="wrap_content"
 android:id="@+id/inGetId"
 android:layout_width="50dip"></EditText>
 <Button android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="@string/btnGetRow"
 android:id="@+id/btnGetId"></Button>
 </LinearLayout>
 <LinearLayout android:layout_width="match_parent"
 android:id="@+id/linearLayout3"
 android:layout_height="wrap_content">
 <EditText android:layout_height="wrap_content"
 android:layout_width="100dip"
 android:id="@+id/inUpdateNama"></EditText>
 <EditText android:layout_height="wrap_content"
 android:layout_width="100dip"
 android:id="@+id/inUpdateHobi"></EditText>
 <Button android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="@string/btnUpdateRow"
 android:id="@+id/btnUpdate"></Button>
 </LinearLayout>
 <View android:layout_width="wrap_content"
 android:id="@+id/view2"
 android:layout_height="1dip"
 android:background="#FF909090"></View>
 <TextView android:layout_height="wrap_content"
 android:layout_width="wrap_content"
 android:id="@+id/textView3"
 android:text="@string/ketDelete"></TextView>
 <LinearLayout android:id="@+id/linearLayout4"
 android:layout_height="wrap_content"
 android:layout_width="match_parent">
 <EditText android:layout_height="wrap_content"
 android:layout_width="50dip"
 android:id="@+id/idDelete"></EditText>
 <Button android:layout_height="wrap_content"
 android:layout_width="wrap_content"
 android:id="@+id/button1"
 android:text="@string/btnDel"></Button>
 </LinearLayout>
 <View android:layout_width="wrap_content"
 android:id="@+id/view2"
 android:layout_height="1dip"
 android:background="#FF909090"></View>
 <TableLayout android:layout_height="wrap_content"
 android:layout_width="match_parent"
 android:id="@+id/tabel_data">
 <TableRow android:id="@+id/tableRow1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content">
 <TextView android:layout_height="wrap_content"
 android:layout_width="50dip"
 android:text="@string/nomorLabel"
 android:id="@+id/no_id"></TextView>
 <TextView android:layout_height="wrap_content"
 android:layout_width="100dip"
 android:text="@string/namaLabel"
 android:id="@+id/nama_id"></TextView>
 <TextView android:layout_width="100dip"
 android:layout_height="wrap_content"
 android:text="@string/hobiLabel"
 android:id="@+id/hobi_id"></TextView>
 </TableRow>
</TableLayout>
</LinearLayout>

4. Next we slightly change Databasemanager.java

package com.db.dua;

 import java.util.ArrayList;

 import android.content.ContentValues;
 import android.content.Context;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.util.Log;
 import android.widget.Toast;

 public class DatabaseManager {

 private static final String ROW_ID = "_id";
 private static final String ROW_NAMA = "nama";
 private static final String ROW_HOBI = "hobi";
 private static final String NAMA_DB = "DatabaseAndroidDua";
 private static final String NAMA_TABEL = "hobiku
 private static final int DB_VERSION = 1;
 private static final String CREATE_TABLE = "create table " +
 NAMA_TABEL+" (" + ROW_ID + " integer PRIMARY KEY autoincrement,"
 + ROW_NAMA+ " text," + ROW_HOBI + " text)";

 private final Context context;
 private DatabaseOpenHelper dbHelper;
 private SQLiteDatabase db;

 public DatabaseManager(Context ctx) {
 this.context = ctx;
 dbHelper = new DatabaseOpenHelper(ctx);
 db = dbHelper.getWritableDatabase();
 }

 private static class DatabaseOpenHelper extends SQLiteOpenHelper {
 public DatabaseOpenHelper(Context context) {
 super(context, NAMA_DB, null, DB_VERSION);
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
 db.execSQL(CREATE_TABLE);
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) {
 db.execSQL("DROP TABLE IF EXISTS " + NAMA_DB);
 onCreate(db);
 }
 }

 public void close() {
 dbHelper.close();
 }

 public void addRow(String nama, String hobi) {

 ContentValues values = new ContentValues();
 values.put(ROW_NAMA, nama);
 values.put(ROW_HOBI, hobi);

 try {
 db.insert(NAMA_TABEL, null, values);
 } catch (Exception e) {
 Log.e("DB ERROR", e.toString());
 e.printStackTrace();
 }
 }

 public ArrayList<ArrayList<Object>> ambilSemuaBaris() {
 ArrayList<ArrayList<Object>> dataArray = new
 ArrayList<ArrayList<Object>>();
 Cursor cur;
 try {
 cur = db.query(NAMA_TABEL, new String[] { ROW_ID, ROW_NAMA,
 ROW_HOBI }, null, null, null, null, null);
 cur.moveToFirst();
 if (!cur.isAfterLast()) {
 do {
 ArrayList<Object> dataList = new ArrayList<Object>();
 dataList.add(cur.getLong(0));
 dataList.add(cur.getString(1));
 dataList.add(cur.getString(2));
 dataArray.add(dataList);
 } while (cur.moveToNext());
 }
 } catch (Exception e) {
 e.printStackTrace();
 Log.e("DEBE ERROR", e.toString());
 Toast.makeText(context, "gagal ambil semua baris:"+e.toString(),Toast.LENGTH_SHORT).show();
 }
 return dataArray;
 }

 public ArrayList<Object> ambilBaris(long rowId) {

 ArrayList<Object> arrbaris = new ArrayList<Object>();
 Cursor cursor;
 try {
 cursor = db.query(NAMA_TABEL, new String[] { ROW_ID,
 ROW_NAMA,ROW_HOBI }, ROW_ID + "=" + rowId, null, null, null,
 null,null);
 cursor.moveToFirst();

 if (!cursor.isAfterLast()) {
 do {
 arrbaris.add(cursor.getLong(0));
 arrbaris.add(cursor.getString(1));
 arrbaris.add(cursor.getString(2));
 } while (cursor.moveToNext());
 String r = String.valueOf(arrbaris);
 Toast.makeText(context, "haha" + r,
 Toast.LENGTH_SHORT).show();
 }
 cursor.close();
 } catch (Exception e) {
 e.printStackTrace();
 Log.e("error", e.toString());
 Toast.makeText(context, "hhii" + e.toString(),
 Toast.LENGTH_SHORT).show();
 }
 return arrbaris;
 }

 public void updateBaris(long rowId, String nama, String hobi) {

 ContentValues cv = new ContentValues();
 cv.put(ROW_NAMA, nama);
 cv.put(ROW_HOBI, hobi);

 try {
 db.update(NAMA_TABEL, cv, ROW_ID + "=" + rowId, null);
 } catch (Exception e) {
 e.printStackTrace();
 Log.e("Db Error", e.toString());
 }
 }

 public void deleteBaris(long idBaris){
 try {
 db.delete(NAMA_TABEL, ROW_ID+"="+idBaris, null);
 } catch (Exception e) {
 e.printStackTrace();
 Log.e("Db Error", e.toString());

}
 }
}

5. Finally we create the DatabaseAndroidDua.java activity.

package com.db.dua;

 import java.util.ArrayList;
 import android.app.Activity;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.TableLayout;
 import android.widget.TableRow;
 import android.widget.TextView;
 import android.widget.Toast;

 public class DatabaseAndroidDua extends Activity {
 DatabaseManager dm;
 EditText nama, hobi, GetId, updateNama, updateHobi,idDel;
 Button addBtn, getIdBtn, updateBtn,delBtn;
 TableLayout tabel4data;// tabel for data

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

 dm = new DatabaseManager(this);
 setupView();
 fungsiBtn();
 updateTable();
 }

 public void setupView() {
 tabel4data = (TableLayout) findViewById(R.id.tabel_data);
 nama = (EditText) findViewById(R.id.inNama);
 hobi = (EditText) findViewById(R.id.inHobi);
 updateNama = (EditText) findViewById(R.id.inUpdateNama);
 updateHobi = (EditText) findViewById(R.id.inUpdateHobi);
 GetId = (EditText) findViewById(R.id.inGetId);
 idDel=(EditText)findViewById(R.id.idDelete);

 addBtn = (Button) findViewById(R.id.btnAdd);
 getIdBtn = (Button) findViewById(R.id.btnGetId);
 updateBtn = (Button) findViewById(R.id.btnUpdate);
 delBtn = (Button) findViewById(R.id.btnDel);
 }

 public void fungsiBtn() {
 addBtn.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 simpKamuta();
 kosongkanField();
 }
 });
 getIdBtn.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View b) {
 ambilBaris();
 }
 });
 updateBtn.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View c) {
 updateBaris();
 kosongkanField();
 }
 });
 delBtn.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View d) {
 // TODO Auto-generated method stub
 deleteData();
 kosongkanField();
 }
 });
 }
 protected void kosongkanField(){
 nama.setText("");
 hobi.setText("");
 updateNama.setText("");
 updateHobi.setText("");
 GetId.setText("");
 idDel.setText("");
 }

 private void deleteData(){
 dm.deleteBaris(Long.parseLong(idDel.getText().toString()));
 updateTable();
 }

 protected void updateBaris() {
 dm.updateBaris(Long.parseLong(GetId.getText().toString()),
 updateNama.getText().toString(),
 updateHobi.getText().toString());
 updateTable();
 }

 private void ambilBaris() {
 try {
 ArrayList<Object> baris;
 baris =
 dm.ambilBaris(Long.parseLong(GetId.getText().toString()));
 updateNama.setText((String) baris.get(1));
 updateHobi.setText((String) baris.get(2));
 } catch (NumberFormatException e) {
 e.printStackTrace();
 Log.e("eror db", e.toString());
 Toast.makeText(getBaseContext(), e.toString(),
 Toast.LENGTH_LONG).show();
 }
 }

 protected void simpKamuta() {
 try {
 dm.addRow(nama.getText().toString(),
 hobi.getText().toString());
 updateTable();
 } catch (Exception e) {
 e.printStackTrace();
 Toast.makeText(getBaseContext(),"gagal simpan,"+
 e.toString(),Toast.LENGTH_LONG).show();
 }
 }

 protected void updateTable() {
 while (tabel4data.getChildCount() > 1) {
 tabel4data.removeViewAt(1);
 }
 ArrayList<ArrayList<Object>> data = dm.ambilSemuaBaris();//
 for (int posisi = 0; posisi < data.size(); posisi++) {
 TableRow tabelBaris = new TableRow(this);
 ArrayList<Object> baris = data.get(posisi);

 TextView idTxt = new TextView(this);
 idTxt.setText(baris.get(0).toString());
 tabelBaris.addView(idTxt);

 TextView namaTxt = new TextView(this);
 namaTxt.setText(baris.get(1).toString());
 tabelBaris.addView(namaTxt);

 TextView hobiTxt = new TextView(this);
 hobiTxt.setText(baris.get(2).toString());
 tabelBaris.addView(hobiTxt);

 tabel4data.addView(tabelBaris);
 }
 }
}

Program Explanation

Ok, in this second part we add features to be able to delete data and change the contents of the table. Look back at the AndroidManager.java class. Here we add 3 new methods, namely

  • The deleteRow() method functions to delete data. Found on lines 140-148
  • The fetchRow() method is used to retrieve data based on ID. Found on lines 96-124 
  • The updateRow() method functions to change data in a particular row. Found on lines 126-138

Now let's look at the AndroidDatabaseDua.java activity. Here we add a new function to delete data, namely the deleteData() method on lines 87-90. Data is deleted based on the id column. For example, if the id you entered is 2, then the data deleted is the data on row 2. The id number is taken from the idDel edittext, then sent to the deleteBaris() method owned by AndroidManager.java.

The next scenario to change the data in the table is divided into 2 stages, first call the data first based on the id then the data is captured and displayed to the edittext. This is where the user can change the name and hobby data, then after pressing the "update" button, the updateBaris() method on lines 92-95 works to capture the contents of the name and hobby edittext then send it to the updateBaris() method belonging to AndroidManager.java. Finally call the updateTable method to update the contents of the table.


Post a Comment

Previous Next

نموذج الاتصال