Android Application Development Training Tutorial                      For more info visit                   http://www.zy...
Android Database TutorialAndroid Database ToolsThe first tool is SQLiteOpenHelper – which is responsible for creating, ope...
AABDatabaseManager.javaimport android.database.sqlite.SQLiteOpenHelper;public class AABDatabaseManager{          private S...
create table database_table ( id integer primary key auto increment not null, table_row_one text, table_row_twotext);Our m...
There is only one other method that is required to be overridden in this class. The onUpdate() method is whereyou would in...
The final argument for the database’s insert() method requires the type ContentValues. A ContentValues objectis a modified...
delete() method, passing it three arguments. The first argument, again, is the table name we are deleting a rowfrom – our ...
values.put(TABLE_ROW_ONE, rowStringOne);         values.put(TABLE_ROW_TWO, rowStringTwo);         // ask the database obje...
pass the value null five times for the next five arguments. That gives us all seven arguments for theSQLiteDatabase object...
return rowArray;}At this point we have a cursor object that has the data from all of the rows of the database table. The n...
array of Strings, see that it is in position zero in that array, and decide that we need to pass “0″ to getLong() toget ba...
** the key is automatically assigned by the database*/public ArrayList<ArrayList<Object>> getAllRowsAsArrays(){        // ...
ArrayList<Object> dataList = new ArrayList<Object>();                                      dataList.add(cursor.getLong(0))...
*/public ArrayList<Object> getRowAsArray(long rowID){        // create an array list to store data from the database row. ...
rowArray.add(cursor.getString(1));                                      rowArray.add(cursor.getString(2));                ...
{    // the Activity or Application that is creating an object from this class.    Context context;    // a reference to t...
* This is an example of how to add a row to a database table* using this class. You should edit this method to suit your* ...
*/public void deleteRow(long rowID){         // ask the database manager to delete the row of given id         try {db.del...
e.printStackTrace();               }      }      /**********************************************************************  ...
);             // move the pointer to position zero in the cursor.             cursor.moveToFirst();             // if the...
/**********************************************************************      * RETRIEVING ALL ROWS FROM THE DATABASE TABLE...
// if there is data after the current cursor position, add it                  // to the ArrayList.                  if (!...
* one. After the class ensures that the database exists, this class        * will open the database for use. Most of this ...
// OTHERWISE, YOU WOULD SPECIFIY HOW TO UPGRADE THEDATABASE.                    }          }}The Application ExplainedIn t...
The Application XMLHere is the complete layout XML file (main.xml):<?xml version="1.0" encoding="utf-8"?><LinearLayout xml...
<Button                          android:id="@+id/add_button"                android:text="@string/add"                and...
<TextView     android:text="@string/update_directions"     android:layout_width="fill_parent"     android:layout_height="w...
android:id="@+id/update_button"                   android:text="@string/update"                   android:layout_width="wr...
<?xml version="1.0" encoding="utf-8"?><resources>  <string name="app_name">Database Application</string>  <string name="ad...
import android.util.Log;import android.widget.Button;import android.widget.EditText;import android.widget.TableLayout;impo...
}         catch (Exception e)         {                    Log.e("ERROR", e.toString());                    e.printStackTr...
updateIDField=                 (EditText)findViewById(R.id.update_id_field);          updateTextFieldOne=            (Edit...
new View.OnClickListener()                   {                            @Override public void onClick(View v) {deleteRow...
The addRow() MethodOur addRow() method collects the input from the first form’s fields. The is handled by calling the getT...
}The deleteRow() MethodThe deleteRow() method is responsible for deleting a row from the database. The database manager th...
The retrieveRow() MethodWhen the user fills in the id field of the last form with a valid id and presses the “get” button,...
}           catch (Exception e)           {                    Log.e("Retrieve Error", e.toString());                    e...
// remove all user input from the Activity                    emptyFormFields();          }          catch (Exception e)  ...
of Objects and tie it to the row that the iterator is currently iterating. For each for item, I need to create aseparate T...
textOne.setText(row.get(1).toString());                    tableRow.addView(textOne);                    TextView textTwo ...
import android.widget.Button;import android.widget.EditText;import android.widget.TableLayout;import android.widget.TableR...
dataTable= (TableLayout)findViewById(R.id.data_table);    textFieldOne= (EditText)findViewById(R.id.text_field_one);    te...
{                   @Override public void onClick(View v) {updateRow();}               }    );    retrieveButton.setOnClic...
e.printStackTrace();      }}private void deleteRow(){      try      {               // ask the database manager to delete ...
updateTextFieldOne.setText((String)row.get(1));                  updateTextFieldTwo.setText((String)row.get(2));        } ...
updateTextFieldOne.setText("");        updateTextFieldTwo.setText("");    }    private void updateTable()    {            ...
Upcoming SlideShare
Loading in...5
×

Android database tutorial

3,664

Published on

Android Training in Kochi, visit http://www.zybotech.in

Published in: Education, Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,664
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
329
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Transcript of "Android database tutorial"

  1. 1. Android Application Development Training Tutorial For more info visit http://www.zybotech.in A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  2. 2. Android Database TutorialAndroid Database ToolsThe first tool is SQLiteOpenHelper – which is responsible for creating, opening, and upgrading a program’sdatabase. The other tool is SQLiteDatabase – which is responsible for communicating changes to the datawithin the database. In this tutorial, first go about creating a database manager class that can be modified andplugged into most apps. This program will make use of both the SQLiteOpenHelper and the SQLiteDatabaseclasses. Afterwards, create a simple application that will instantiate and use our new database manager class.Setting Up the SQLiteOpenHelper for UseHow our classes are layed outThe first thing is extend the SQLiteOpenHelper class so that it creates our database with the appropriatestructure that our application needs. The SQLiteOpenHelper class is abstract. This means we need to extend theclass with a concrete class, overriding the appropriate methods. We also need to make available to this class adatabase name, table name, and column names. The best way to handle the variables is with constants.Constants ensure that the correct names are always used.The SQLiteOpenHelper class internal to our database manager class. All of database constants will be insidethe database manager class so they are accessible from both our SQLiteOpenHelper class and our maindatabase class. This setup may not be common practice; easier to work with. The SQLDatabase object,responsible for communicating with the database, is also going to be in the database manager class. This wayall of our resources are available throughout the manager class.How our database is structuredIn this a single table with three columns: one column is the row id (id), and the other two columns are Strings(table_row_one and table_row_two). All of these column names as well as a database version number (more ondatabase version later) are going to be constants.Our base class containing database constants, a SQLDatabase object, and an internal class that extendsSQLiteOpenHelper. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  3. 3. AABDatabaseManager.javaimport android.database.sqlite.SQLiteOpenHelper;public class AABDatabaseManager{ private SQLiteDatabase db; // a reference to the database manager class. private final String DB_NAME = "database_name"; // the name of our database private final int DB_VERSION = 1; // the version of the database // the names for our database columns private final String TABLE_NAME = "database_table"; private final String TABLE_ROW_ID = "id"; private final String TABLE_ROW_ONE = "table_row_one"; private final String TABLE_ROW_TWO = "table_row_two"; // TODO: write the constructor and methods for this class // the beginnings our SQLiteOpenHelper class private class CustomSQLiteOpenHelper extends SQLiteOpenHelper { // TODO: override the constructor and other methods for the parent class }}Now customize the helper class to create our database according to specification.Overriding the SQLiteOpenHelper methods.SQLiteOpenHelper has to know how to design the database. By overriding the onCreate() method with theproper code for creating the database. It’s as simple as creating a SQLite query string and passing it to theSQLiteDatabase object (db). SQLite query structure is out of scope for discussion here so I will not go intodetail here.The SQLite query String needs to read: A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  4. 4. create table database_table ( id integer primary key auto increment not null, table_row_one text, table_row_twotext);Our method override with the query String built from constants looks like this:@Overridepublic void onCreate(SQLiteDatabase db){ // the SQLite query string that will create our 3 column database table. String newTableQueryString = "create table " + TABLE_NAME + " (" + TABLE_ROW_ID + " integer primary key auto increment not null," + TABLE_ROW_ONE + " text," + TABLE_ROW_TWO + " text" + ");"; // execute the query string to the database. db.execSQL(newTableQueryString);}We need to override the constructor as well. We pass the super constructor the context, the database nameconstant, null, and the database version constant. The null argument has to do with a custom Cursor Factory.The Cursor Factory is them creates the containers in which our data is passed out of the database. When data iscollected from the database, it comes in the form of a Cursor. Cursors are a form of Java collection similar to anArrayList. We are using the default Cursor Factory so we can just pass in null. Constructor override is:public CustomSQLiteOpenHelper (Context context){ super(context, DB_NAME, null, DB_VERSION);} A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  5. 5. There is only one other method that is required to be overridden in this class. The onUpdate() method is whereyou would include the programming required to revise the structure of the database. The override method willbe left blank as follows:@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){ // NOTHING TO DO HERE. THIS IS THE ORIGINAL DATABASE VERSION. // OTHERWISE, YOU WOULD SPECIFIY HOW TO UPGRADE THE DATABASE // FROM OLDER VERSIONS.}Now move on to creating our database manager class.Creating the Database Manager ClassWe extended the class that is responsible for creating and updating the database. We also created aSQLiteDatabase object and some database constants. All of this was wrapped in the beginnings of a databasemanager class. Now we are going to create this manager class. One of its main purposes is to communicatewith the SQLiteDatabase object. Our class will call methods of the database object; the database object willsend queries to the database and return data to our manager class for output to our application.We created the outline for our new class (AABDatabaseManager). We now need to include functionality in ourclass for retrieving, adding, and updating data to and from the database. There are five different methods:addRow(), deleteRow(), updateRow(), getRow(), and getAllRows().The addRow() MethodOur addRow() method of the database manager class is going to take two String arguments and ask the databaseobject to add them as a new row in the given database table. The database object has an insert() method that weneed to call. The insert() method takes three arguments.>The first argument is the table name. We will pass the constant TABLE_NAME here.The next argument requires a nullColumnHack type. This has to do with whether the row can be empty or not.We are going to pass in null as the variable here. In this instance, our database will not allow empty rows. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  6. 6. The final argument for the database’s insert() method requires the type ContentValues. A ContentValues objectis a modified java collection that contains key/value pairs. We need to create a ContentValues object and pass ittwo key/value pairs to satisfy the database requirement (the id column will fill in automatically, that leaves thetext_one and text_two columns). Once we have our ContentValues object, we can call the insert() method toadd the new data to the database. Database method calls inside of try/catch blocks to pass error messages to thelog for debugging. Let’s take a look at this code:public void addRow(String rowStringOne, String rowStringTwo){ // this is a key value pair holder used by androids SQLite functions ContentValues values = new ContentValues(); // this is how you add a value to a ContentValues object // we are passing in a key string and a value string each time values.put(TABLE_ROW_ONE, rowStringOne); values.put(TABLE_ROW_TWO, rowStringTwo); // ask the database object to insert the new data try { db.insert(TABLE_NAME, null, values); } catch(Exception e) { Log.e("DB ERROR", e.toString()); // prints the error message to the log e.printStackTrace(); // prints the stack trace to the log }}The deleteRow() MethodThe deleteRow() method is a little simpler. It is going to take one argument, long rowID. We use a Long insteadof an Integer because integers in SQLite are larger than integers in Java. Collecting data from a SQLitedatabase and storing it in a Java Integer type may result in data loss. Using Long when dealing with SQLite inJava is recommended. Once we pass in our rowID argument, we are going to call the SQLiteDatabase object’s A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  7. 7. delete() method, passing it three arguments. The first argument, again, is the table name we are deleting a rowfrom – our TABLE_NAME constant. The second argument we pass is the SQLite WHERE clause without theword “where”. We need the “id” to equal the id we want to be deleted. Since this is a String argument, we canbuild the String inside the method call like this: TABLE_ROW_ID + “=” + rowID. Here is the deleteRow()method:public void deleteRow(long rowID){ // ask the database manager to delete the row of given id try { db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null); } catch (Exception e) { Log.e("DB ERROR", e.toString()); e.printStackTrace(); }}The updateRow() MethodThe updateRow() method requires three arguments: the rowID, rowStringOne, and rowStringTwo. Like in theaddRow() method, create ContentValues object and give it two key/value pairs. Once everything is ready, wesend it to the database object inside of a try/catch block.The SQLite database object has an update() method that takes four arguments. The first argument is the tablename. The next argument is the ContentValues object. The third argument is the SQLite WHERE clause. Againwe put this string together inside of the method call. The final argument is the WHERE clause arguments.Typically, you could specify a String array of arguments to pass in for the WHERE conditions. For this casethere is only one argument, so we will pass in null. Here is the entire method:public void updateRow(long rowID, String rowStringOne, String rowStringTwo){ // this is a key value pair holder used by androids SQLite functions ContentValues values = new ContentValues(); A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  8. 8. values.put(TABLE_ROW_ONE, rowStringOne); values.put(TABLE_ROW_TWO, rowStringTwo); // ask the database object to update the database row of given rowID try {db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null);} catch (Exception e) { Log.e("DB Error", e.toString()); e.printStackTrace(); }}The getRowAsArray() and getAllRowsAsArrays() MethodsThese next two methods are going to exemplify the use of Cursor objects. When we retrieve a single row ormultiple rows from the SQLiteDatabase object, we receive back a Cursor. These Cursor objects act ascontainers and iterators for the rows of data that are returned. I chose to have our methods convert the datainside the Cursor to ArrayLists. The getAllRowsAsArrays() method and not the getRowAsArray() method Before we get started, cover the casting required for the ArrayList. Casting an ArrayList looks like this:ArrayList<ObjectType>. Inside of the brackets is where you specify what type of objects will be stored insideof the ArrayList. In this example, we have ArrayLists of unspecified objects inside of an ArrayList. If we wereto declare an ArrayList of Objects. We would write it: ArrayList<Object>().ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();Let’s move on to the getRowsAsArrays() method. The first thing we do is create an ArrayList of ArrayLists ofObjects to store the data in the method. I just covered how to do that. The next thing we need to do is create ourCursor object. I declare the Cursor object. Then, when I create it, I do so by calling the database object’squery() method. Remember that the query() method returns a Cursor object. Our query() method takes sevenarguments. Fortunately, we only need to worry about the first two to collect data from all rows in the database.The first argument is the table name to gather data from. The second argument is an array of the names(Strings) of each column we want the query to return. If we want data from two columns, we need two columnnames. If we want data from five columns, we would need five column names. In our case, we are going tocollect data from all three columns in our example table: the id, table_row_one, and table_row_two. We can A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  9. 9. pass the value null five times for the next five arguments. That gives us all seven arguments for theSQLiteDatabase object’s query() method.Our getRowAsArray() method passes a third argument to the query() method. This argument, a String, satisfiesthe WHERE clause by specifying “TABLE_ROW_ID=rowID”. This is similar to the deleteRow() method’sWHERE clause that I covered earlier in this section. So when we write the getRowAsArray() method. We passin three arguments and four null arguments to the SQLiteDatabase query() method.In this code the database query() method call into seven lines. I prefer to do this for readability – you may ormay not want to do the same.public ArrayList<Object> getRowAsArray(long rowID){ ArrayList<Object> rowArray = new ArrayList<Object>(); Cursor cursor; try { // this method call is spread out over seven lines as a personal preference cursor = db.query ( TABLE_NAME, new String[] { TABLE_ROW_ID, TABLE_ROW_ONE,TABLE_ROW_TWO }, TABLE_ROW_ID + "=" + rowID, null, null, null, null, null ); // TODO Move the data from the cursor to the arraylist. } catch (SQLException e) { Log.e("DB ERROR", e.toString()); e.printStackTrace(); } A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  10. 10. return rowArray;}At this point we have a cursor object that has the data from all of the rows of the database table. The next thingwe are going to do is collect this data from the cursor and store it in an ArrayList. Since the cursor object filleditself one item at a time, the cursor’s pointer is at the end of the cursor. After each letter is typed, the pointer(the little arrow showing you where the next letter is going to go) points at the next available space to type anew letter. Our cursor object inserted data into each space and now it’s pointer is at the end of the data that itentered. We want to read the data from the beginning so we need to move the pointer there. We do this with theCursor’s moveToFirst () function.Once the pointer is at the front of the data, we can iterate through the cursor and collect the data as we go. Let’siterate through the cursor with a do/while block. We are going to “do” the data collecting “while” the Cursor’smoveToNext() method returns false. The moveToNext() method simply tries to move the pointer to the next rowof data. If there are any available rows ahead, it goes to the “next” one and returns true. If there are no morerows, the method does nothing and returns false.do{ // TODO: put data from current cursor row into an array // TODO: put the new array into the array of arrays}// try to move the cursors pointer forward one position.while (cursor.moveToNext());With our pointer now on the first row of data, we need to collect the data from that row from within the doblock. The first thing is create a new ArrayList of Objects. In order to add the first piece of data I use one of thecursor’s “get” methods. There is a “get” method for each of the cursor’s supported data types. We know thedata from the first column of data is the “id” of type Long. This means we need to use the cursor’s getLong()method.Each of these “get” methods takes a single argument that represents the column of data we want the data from.When we created the cursor object, the second argument we passed to the query() method was an array of threeStrings. The position of each of these column name Strings in the array of Strings corresponds to the neededargument in the Cursor’s get functions. If we want the TABLE_ROW_ID (“id”) column’s data, we look at the A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  11. 11. array of Strings, see that it is in position zero in that array, and decide that we need to pass “0″ to getLong() toget back the “id” of the first row.All we have to do to get the “id” into the ArrayList is call the ArrayList’s add() method, passing incursor.getLong(0) as the argument. cursor.getLong(0) will pass the data into add() which will add the data tothe ArrayList. After that we do the same for the next two positions of data using getString() twice – passing in“1″ and “2″ consecutively.Here is the do while list that will collect the data from the ArrayList:do{ ArrayList<Object> dataList = new ArrayList<Object>(); dataList.add(cursor.getLong(0)); dataList.add(cursor.getString(1)); dataList.add(cursor.getString(2)); dataArrays.add(dataList);}// move the cursors pointer up one position.while (cursor.moveToNext());Placed this do/while block inside of an if block so that it only runs “if” !cursor.isAfterLast() returns true. Thatis, once the cursor’s pointer was moved to the beginning of the cursor, “if” the pointer is not after the last row(ie., the beginning is not the end), then run the do/while code block. Once our do/while code completes, we canreturn our newly created ArrayList and we are done with writing this method.Let’s take a look at the two methods we just discussed./*********************************************************************** RETRIEVING ALL ROWS FROM THE DATABASE TABLE** This is an example of how to retrieve all data from a database* table using this class. You should edit this method to suit your* needs. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  12. 12. ** the key is automatically assigned by the database*/public ArrayList<ArrayList<Object>> getAllRowsAsArrays(){ // create an ArrayList that will hold all of the data collected from // the database. ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>(); // this is a database call that creates a "cursor" object. // the cursor object store the information collected from the // database and is used to iterate through the data. Cursor cursor; try { // ask the database object to create the cursor. cursor = db.query( TABLE_NAME, new String[]{TABLE_ROW_ID, TABLE_ROW_ONE,TABLE_ROW_TWO}, null, null, null, null, null ); // move the cursors pointer to position zero. cursor.moveToFirst(); // if there is data after the current cursor position, add it // to the ArrayList. if (!cursor.isAfterLast()) { do { A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  13. 13. ArrayList<Object> dataList = new ArrayList<Object>(); dataList.add(cursor.getLong(0)); dataList.add(cursor.getString(1)); dataList.add(cursor.getString(2)); dataArrays.add(dataList); } // move the cursors pointer up one position. while (cursor.moveToNext()); } } catch (SQLException e) { Log.e("DB Error", e.toString()); e.printStackTrace(); } // return the ArrayList that holds the data collected from // the database. return dataArrays;}/*********************************************************************** RETRIEVING A ROW FROM THE DATABASE TABLE** This is an example of how to retrieve a row from a database table* using this class. You should edit this method to suit your needs.** @param rowID the id of the row to retrieve* @return an array containing the data from the row A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  14. 14. */public ArrayList<Object> getRowAsArray(long rowID){ // create an array list to store data from the database row. // I would recommend creating a JavaBean compliant object // to store this data instead. That way you can ensure // data types are correct. ArrayList<Object> rowArray = new ArrayList<Object>(); Cursor cursor; try { // this is a database call that creates a "cursor" object. // the cursor object store the information collected from the // database and is used to iterate through the data. cursor = db.query ( TABLE_NAME, new String[] { TABLE_ROW_ID, TABLE_ROW_ONE,TABLE_ROW_TWO }, TABLE_ROW_ID + "=" + rowID, null, null, null, null, null ); // move the pointer to position zero in the cursor. cursor.moveToFirst(); // if there is data available after the cursors pointer, add // it to the ArrayList that will be returned by the method. if (!cursor.isAfterLast()) { do { rowArray.add(cursor.getLong(0)); A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  15. 15. rowArray.add(cursor.getString(1)); rowArray.add(cursor.getString(2)); } while (cursor.moveToNext()); } // let java know that you are through with the cursor. cursor.close(); } catch (SQLException e) { Log.e("DB ERROR", e.toString()); e.printStackTrace(); } // return the ArrayList containing the given row from the database. return rowArray;}The AABDatabaseManager.java classpackage com.anotherandroidblog.tools.database;import java.util.ArrayList;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.SQLException;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log;public class AABDatabaseManager A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  16. 16. { // the Activity or Application that is creating an object from this class. Context context; // a reference to the database used by this application/object private SQLiteDatabase db; // These constants are specific to the database. They should be // changed to suit your needs. private final String DB_NAME = "database_name"; private final int DB_VERSION = 1; // These constants are specific to the database table. They should be // changed to suit your needs. private final String TABLE_NAME = "database_table"; private final String TABLE_ROW_ID = "id"; private final String TABLE_ROW_ONE = "table_row_one"; private final String TABLE_ROW_TWO = "table_row_two"; public AABDatabaseManager(Context context) { this.context = context; // create or open the database CustomSQLiteOpenHelper helper = new CustomSQLiteOpenHelper(context); this.db = helper.getWritableDatabase(); } /********************************************************************** * ADDING A ROW TO THE DATABASE TABLE * A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  17. 17. * This is an example of how to add a row to a database table* using this class. You should edit this method to suit your* needs.** the key is automatically assigned by the database* @param rowStringOne the value for the rows first column* @param rowStringTwo the value for the rows second column*/public void addRow(String rowStringOne, String rowStringTwo){ // this is a key value pair holder used by androids SQLite functions ContentValues values = new ContentValues(); values.put(TABLE_ROW_ONE, rowStringOne); values.put(TABLE_ROW_TWO, rowStringTwo); // ask the database object to insert the new data try{db.insert(TABLE_NAME, null, values);} catch(Exception e) { Log.e("DB ERROR", e.toString()); e.printStackTrace(); }}/*********************************************************************** DELETING A ROW FROM THE DATABASE TABLE** This is an example of how to delete a row from a database table* using this class. In most cases, this method probably does* not need to be rewritten.** @param rowID the SQLite database identifier for the row to delete. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  18. 18. */public void deleteRow(long rowID){ // ask the database manager to delete the row of given id try {db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null);} catch (Exception e) { Log.e("DB ERROR", e.toString()); e.printStackTrace(); }}/*********************************************************************** UPDATING A ROW IN THE DATABASE TABLE** This is an example of how to update a row in the database table* using this class. You should edit this method to suit your needs.** @param rowID the SQLite database identifier for the row to update.* @param rowStringOne the new value for the rows first column* @param rowStringTwo the new value for the rows second column*/public void updateRow(long rowID, String rowStringOne, String rowStringTwo){ // this is a key value pair holder used by androids SQLite functions ContentValues values = new ContentValues(); values.put(TABLE_ROW_ONE, rowStringOne); values.put(TABLE_ROW_TWO, rowStringTwo); // ask the database object to update the database row of given rowID try {db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null);} catch (Exception e) { Log.e("DB Error", e.toString()); A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  19. 19. e.printStackTrace(); } } /********************************************************************** * RETRIEVING A ROW FROM THE DATABASE TABLE * * This is an example of how to retrieve a row from a database table * using this class. You should edit this method to suit your needs. * * @param rowID the id of the row to retrieve * @return an array containing the data from the row */ public ArrayList<Object> getRowAsArray(long rowID) { // create an array list to store data from the database row. // I would recommend creating a JavaBean compliant object // to store this data instead. That way you can ensure // data types are correct. ArrayList<Object> rowArray = new ArrayList<Object>(); Cursor cursor; try { // this is a database call that creates a "cursor" object. // the cursor object store the information collected from the // database and is used to iterate through the data. cursor = db.query ( TABLE_NAME, new String[] { TABLE_ROW_ID, TABLE_ROW_ONE,TABLE_ROW_TWO }, TABLE_ROW_ID + "=" + rowID, null, null, null, null, null A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  20. 20. ); // move the pointer to position zero in the cursor. cursor.moveToFirst(); // if there is data available after the cursors pointer, add // it to the ArrayList that will be returned by the method. if (!cursor.isAfterLast()) { do { rowArray.add(cursor.getLong(0)); rowArray.add(cursor.getString(1)); rowArray.add(cursor.getString(2)); } while (cursor.moveToNext()); } // let java know that you are through with the cursor. cursor.close(); } catch (SQLException e) { Log.e("DB ERROR", e.toString()); e.printStackTrace(); } // return the ArrayList containing the given row from the database. return rowArray;} A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  21. 21. /********************************************************************** * RETRIEVING ALL ROWS FROM THE DATABASE TABLE * * This is an example of how to retrieve all data from a database * table using this class. You should edit this method to suit your * needs. * * the key is automatically assigned by the database */ public ArrayList<ArrayList<Object>> getAllRowsAsArrays() { // create an ArrayList that will hold all of the data collected from // the database. ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>(); // this is a database call that creates a "cursor" object. // the cursor object store the information collected from the // database and is used to iterate through the data. Cursor cursor; try { // ask the database object to create the cursor. cursor = db.query( TABLE_NAME, new String[]{TABLE_ROW_ID, TABLE_ROW_ONE,TABLE_ROW_TWO}, null, null, null, null, null ); // move the cursors pointer to position zero. cursor.moveToFirst(); A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  22. 22. // if there is data after the current cursor position, add it // to the ArrayList. if (!cursor.isAfterLast()) { do { ArrayList<Object> dataList = new ArrayList<Object>(); dataList.add(cursor.getLong(0)); dataList.add(cursor.getString(1)); dataList.add(cursor.getString(2)); dataArrays.add(dataList); } // move the cursors pointer up one position. while (cursor.moveToNext()); } } catch (SQLException e) { Log.e("DB Error", e.toString()); e.printStackTrace(); } // return the ArrayList that holds the data collected from // the database. return dataArrays;}/*** This class is designed to check if there is a database that currently* exists for the given program. If the database does not exist, it creates A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  23. 23. * one. After the class ensures that the database exists, this class * will open the database for use. Most of this functionality will be * handled by the SQLiteOpenHelper parent class. The purpose of extending * this class is to tell the class how to create (or update) the database. * * @author Randall Mitchell *private class CustomSQLiteOpenHelper extends SQLiteOpenHelper { public CustomSQLiteOpenHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); }@Override public void onCreate(SQLiteDatabase db) { // This string is used to create the database. It should // be changed to suit your needs. String newTableQueryString = "create table " + TABLE_NAME +" (" + TABLE_ROW_ID + " integer primary key autoincrement not null," + TABLE_ROW_ONE + " text," +TABLE_ROW_TWO + " text" + ");"; // execute the query string to the database. db.execSQL(newTableQueryString); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // NOTHING TO DO HERE. THIS IS THE ORIGINAL DATABASE VERSION. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  24. 24. // OTHERWISE, YOU WOULD SPECIFIY HOW TO UPGRADE THEDATABASE. } }}The Application ExplainedIn the database there are three columns: id (integer), table_row_one (string), and table_row_two (string). Ouractivity is going to have three forms for the user to adjust data within the database. The three forms handleadding, deleting, and editing rows. There will also be instruction that tell the user on how to use each of theforms. Below the three forms is a table that displays the database table data to the user. The table consists ofone column for each database table column and one row for each database row. Let’s take a look at each of theforms.Form for Adding DataThe first form is for adding data to the database. The form will have two form fields where the user can entervalues. The form fields correspond to table_row_one and table_row_two in the database. After the two formfields, there is a “submit” button for the user to submit entered data. The application’s database object willautomatically assign an id to the new data.Form for Deleting DataThe second form is used to delete a row from the database. It will have a single form field where the user willenter a value that corresponds to an id in the database table. Next to the id field is a delete button for the user tosubmit the form.Form For Retrieving and Editing DataThe final form will allow the user to change a row of data. This form will have two buttons and three formfields. The first form field is for the user to enter an id. After this form field is a “get” button that the user canuse to retrieve data into the next two form fields. Then the user can change the data in these fields and hit the“update” button to update the data. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  25. 25. The Application XMLHere is the complete layout XML file (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" > <!-- ADD A DATA ENTRY FORM --> <TextView android:text="@string/add_directions" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > <EditText android:id="@+id/text_field_one" android:layout_width="wrap_content" android:layout_height="wrap_content" android:minWidth="100px" /> <EditText android:id="@+id/text_field_two" android:layout_width="wrap_content" android:layout_height="wrap_content" android:minWidth="100px" /> A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  26. 26. <Button android:id="@+id/add_button" android:text="@string/add" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <!-- DELETE A DATA ENTRY FORM --><TextView android:text="@string/delete_directions" android:layout_width="fill_parent" android:layout_height="wrap_content" /><LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > <EditText android:id="@+id/id_field" android:layout_width="wrap_content" android:layout_height="wrap_content" android:minWidth="100px" /> <Button android:id="@+id/delete_button" android:text="@string/delete" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <!-- UPDATE A DATA ENTRY FORM --> A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  27. 27. <TextView android:text="@string/update_directions" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" > <EditText android:id="@+id/update_id_field" android:layout_width="wrap_content" android:layout_height="wrap_content" android:minWidth="45px" /> <Button android:id="@+id/retrieve_button" android:text="@string/retrieve" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/update_text_field_one" android:layout_width="wrap_content" android:layout_height="wrap_content" android:minWidth="70px" /> <EditText android:id="@+id/update_text_field_two" android:layout_width="wrap_content" android:layout_height="wrap_content" android:minWidth="70px" /> <Button A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  28. 28. android:id="@+id/update_button" android:text="@string/update" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <!-- THE DATA TABLE --> <TableLayout android:id="@+id/data_table" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TableRow> <TextView android:text="@string/th_id" android:minWidth="50px" /> <TextView android:text="@string/th_text_one" android:minWidth="125px" /> <TextView android:text="@string/th_text_two" android:minWidth="125px" /> </TableRow> </TableLayout></LinearLayout>And here is the strings.xml resource file: A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  29. 29. <?xml version="1.0" encoding="utf-8"?><resources> <string name="app_name">Database Application</string> <string name="add_directions">Fill in both fields with text and click the "add" button.</string> <string name="add">add</string> <string name="delete_directions">To delete a row, type the "id" of the row in the field provided and pressthe "delete" button.</string> <string name="delete">delete</string> <string name="update_directions">To update a row, type the "id" of the row in the first field and type thenew information into the next two fields.</string> <string name="retrieve">get</string> <string name="update">update</string> <string name="th_id">ID</string> <string name="th_text_one">Text Field One</string> <string name="th_text_two">Text Field Two</string></resources>Now move on to the Activity class.The Main ActivityThe first thing we need to do is establish some object variables. There should be a variable for each of the formfields buttons. We will also need declarations for our table object and our fancy new database manager object.Let’s take a look at the beginning of our activity class:package com.anotherandroidblog.tools.database;import java.util.ArrayList;import android.app.Activity;import android.os.Bundle; A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  30. 30. import android.util.Log;import android.widget.Button;import android.widget.EditText;import android.widget.TableLayout;import android.widget.TableRow;import android.widget.TextView;public class DatabaseExampleActivity extends Activity{ // the text fields that users input new data into EditText textFieldOne, textFieldTwo, idField, updateIDField, updateTextFieldOne,updateTextFieldTwo; // the buttons that listen for the user to select an action Button addButton, deleteButton, retrieveButton, updateButton; // the table that displays the data TableLayout dataTable; // the class that opens or creates the database and makes sql calls to it AABDatabaseManager db; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { // this try catch block returns better error reporting to the log try { // Android OS specific calls super.onCreate(savedInstanceState); setContentView(R.layout.main); // TODO complete the setup operations A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  31. 31. } catch (Exception e) { Log.e("ERROR", e.toString()); e.printStackTrace(); } // TODO create the rest of the methods }The try/catch block is a method is used for improved error reporting in Android.Connecting the Layout to JavaIn our Java code, we need to connect our variables to the fields, buttons, and table that were all created in ourXML file. I am going to make a method that specifically handles this task: setupViews(). The method used inAndroid to connect a variable to an XML object is to use the findViewByID() method. This method takes oneargument – the resource id of the view widget. The important thing to know about findViewByID() is that weneed to “cast” it to a specific widget type. We do this by placing the “type” in parenthesis in front of themethod call. We will use the assignment(=) operator to assign each variable to the type cast object returned byfindViewByID. There needs to be one statement for each of the view widgets we wish to work with in Java. Letstake a look at the method code:/*** creates references and listeners for the GUI interface*/private void setupViews(){ // THE DATA TABLE dataTable= (TableLayout)findViewById(R.id.data_table); // THE DATA FORM FIELDS textFieldOne= (EditText)findViewById(R.id.text_field_one); textFieldTwo= (EditText)findViewById(R.id.text_field_two); idField= (EditText)findViewById(R.id.id_field); A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  32. 32. updateIDField= (EditText)findViewById(R.id.update_id_field); updateTextFieldOne= (EditText)findViewById(R.id.update_text_field_one); updateTextFieldTwo= (EditText)findViewById(R.id.update_text_field_two); // THE BUTTONS addButton = (Button)findViewById(R.id.add_button); deleteButton = (Button)findViewById(R.id.delete_button); retrieveButton = (Button)findViewById(R.id.retrieve_button); updateButton = (Button)findViewById(R.id.update_button);}This and several other methods will be called from within onCreate() as a means of setting up our Activity.Enabling the ButtonsCreate one method for enabling the buttons and then a methodfor each of the buttons: addRow(), deleteRow(), retrieveRow(), and updateRow(). These methods will be calledwhen a particular button is pushed. Here is the addButtonListeners() method that ties each button to the correctmethod:/*** adds listeners to each of the buttons and sets them to call relevant methods*/private void addButtonListeners(){ addButton.setOnClickListener ( new View.OnClickListener() { @Override public void onClick(View v) {addRow();} } ); deleteButton.setOnClickListener ( A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  33. 33. new View.OnClickListener() { @Override public void onClick(View v) {deleteRow();} } ); updateButton.setOnClickListener ( new View.OnClickListener() { @Override public void onClick(View v) {updateRow();} } ); retrieveButton.setOnClickListener ( new View.OnClickListener() { @Override public void onClick(View v) {retrieveRow();} } );}A few note worthy points. We attach OnClickListener objects to a button by using the button’ssetOnClickListener() method. It is common to create the OnClickListener objects inside of the method call asseen here. When we create these generic listeners, we need to override their onClick() method with our desiredcode. The desired code will simply be a call to the appropraite method.Communicating with the Database Manager ObjectWe have each of the buttons in our application tied to OnClickListeners. When the user clicks a button, thelistener will call a specific method. We need to create those methods. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  34. 34. The addRow() MethodOur addRow() method collects the input from the first form’s fields. The is handled by calling the getText()method of the TextView form fields combined with the toString() method of the getText() return type. It lookslike this: textFieldOne.getText().toString(). It uses this data as arguments in a call to the database manager’saddRow() method. After the data is sent to the database, addRow()/*** adds a row to the database based on information contained in the* add row form fields.*/private void addRow(){ try { // ask the database manager to add a row given the two strings // this is addRow() in the activity calling addRow() in the database object db.addRow ( textFieldOne.getText().toString(), textFieldTwo.getText().toString() ); // request the table be updated updateTable(); // remove all user input from the Activity emptyFormFields(); } catch (Exception e) { Log.e("Add Error", e.toString()); e.printStackTrace(); } A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  35. 35. }The deleteRow() MethodThe deleteRow() method is responsible for deleting a row from the database. The database manager that wecreated earlier has a corresponding deleteRow() method. We collect and pass the value that the user enters intothe idField with idField.getText().toString(). Once the data row is deleted, we update our table widget andempty our form fields. Here is our method code:/*** deletes a row from the database with the id number in the corresponding* user entry field*/private void deleteRow(){ try { // ask the database manager to delete the row with the give rowID. db.deleteRow(Long.parseLong(idField.getText().toString())); // request the table be updated updateTable(); // remove all user input from the Activity emptyFormFields(); } catch (Exception e) { Log.e("Delete Error", e.toString()); e.printStackTrace(); }} A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  36. 36. The retrieveRow() MethodWhen the user fills in the id field of the last form with a valid id and presses the “get” button, retrieveRow() iscalled. Let’s go over the code inside of retrieveRow(). First we declare a local ArrayList object and instantiatesit by calling the datatabase mananger’s getRowAsArray() method. The getRowAsArray() method in the databasemanager takes a Long as its only argument – the row id. We collect the value from the id form field as a String.order to covert the String to a Long, we use the Long class’ static method parseLong(String). The Long cannow be passed to getRowAsArray(). Here is that code:ArrayList<Object> row;row = db.getRowAsArray( Long.parseLong( updateIDField.getText().toString() ) );Once we have our ArrayList populated with data, we can pass that data to the two remaining form fields. We dothis using the setText() method of the EditText widgets.Because of the way we set up the database manager, Java doesn’t know what types of values are in theArrayList. This means we need to cast the ArrayList items of unkown type to String using a(String) cast.Here is the code for our retrieveRow() method./*** retrieves a row from the database with the id number in the corresponding* user entry field*/private void retrieveRow(){ try { // The ArrayList that holds the row data ArrayList<Object> row; // ask the database manager to retrieve the row with the given rowID row = db.getRowAsArray(Long.parseLong(updateIDField.getText().toString())); // update the form fields to hold the retrieved data updateTextFieldOne.setText((String)row.get(1)); updateTextFieldTwo.setText((String)row.get(2)); A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  37. 37. } catch (Exception e) { Log.e("Retrieve Error", e.toString()); e.printStackTrace(); }}The updateRow() MethodOur Activity’s updateRow() method calls the database mananger’s updateRow() method, passing it threearguments. The first value passed is a row id. Here again, we use Long.parseLong(String), passing it the Stringfrom the updateIDField() method. The next two arguments we pass updateRow() are String values that weretrieve from updateTextFieldOne() and updateTextFieldTwo(). The database manager updates the given rowand we can update our table and empty our form fields. Here is updateRow()/*** updates a row with the given information in the corresponding user entry* fields*/private void updateRow(){ try { // ask the database manager to update the row based on the information // found in the corresponding user entry fields db.updateRow ( Long.parseLong(updateIDField.getText().toString()), updateTextFieldOne.getText().toString(), updateTextFieldTwo.getText().toString() ); // request the table be updated updateTable(); A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  38. 38. // remove all user input from the Activity emptyFormFields(); } catch (Exception e) { Log.e("Update Error", e.toString()); e.printStackTrace(); }}The updateTable() MethodThe table I set up has column headers inside of the first row of our table. When updateTable() is called, itdeletes all the table rows except the top row (of headers), and then recreates the rows based upon the currentstate of the database.Deleting the rows is handled by a while block. We can determine how many rows are in the table using it’sgetChildCount() method. The while block logic reads “while the child count is greater than one, delete the rowin the second position”. This will delete all rows except the first row. Don’t forget that the count starts at zero,so the second position is “1″. This is our while block.while (dataTable.getChildCount() > 1){ dataTable.removeViewAt(1);}Now, we have an empty table ready for use. We need to get that data ready to enter into the table. First, Ideclare an ArrayList of ArrayLists of Objects and instantiate it making it the return value of the databasemanager’s getAllRowsAsArray() method as follows.ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();Then we can iterate through data and create table rows as we go. I set up an iteration block that will create arow, fill it with data, and add it to our table with each iteration of the ArrayList. Inside of our block, I createand instantiate a new TableRow object: “TableRow tableRow = new TableRow(this);“. I declare an ArrayList A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  39. 39. of Objects and tie it to the row that the iterator is currently iterating. For each for item, I need to create aseparate TextView object and add it to the new TableRow. Finally, I add the TableRow to the data table usingthe table’s addView() method.Here is the updateTable() method:private void updateTable(){ // delete all but the first row. remember that the count // starts at one and the index starts at zero while (dataTable.getChildCount() > 1) { // while there are at least two rows in the table widget, delete // the second row. dataTable.removeViewAt(1); } // collect all row data from the database and // store it in a two dimensional ArrayList ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays(); // iterate the ArrayList, create new rows each time and add them // to the table widget. for (int position=0; position < data.size(); position++) { TableRow tableRow= new TableRow(this); ArrayList<Object> row = data.get(position); TextView idText = new TextView(this); idText.setText(row.get(0).toString()); tableRow.addView(idText); TextView textOne = new TextView(this); A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  40. 40. textOne.setText(row.get(1).toString()); tableRow.addView(textOne); TextView textTwo = new TextView(this); textTwo.setText(row.get(2).toString()); tableRow.addView(textTwo); dataTable.addView(tableRow); }}That’s it for updating the table widget. The only thing left to cover is the little helper class for clearing the formdata. All it does is call each of the application’s form field’s setText() methods, passing in an empty String (“”).Here is the code for that:private void emptyFormFields(){ textFieldOne.setText(""); textFieldTwo.setText(""); idField.setText(""); updateIDField.setText(""); updateTextFieldOne.setText(""); updateTextFieldTwo.setText("");}The entire code for the Activity is next.package com.anotherandroidblog.tools.database;import java.util.ArrayList;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.View; A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  41. 41. import android.widget.Button;import android.widget.EditText;import android.widget.TableLayout;import android.widget.TableRow;import android.widget.TextView;public class DatabaseExampleActivity extends Activity{ EditText textFieldOne, textFieldTwo, idField, updateIDField, updateTextFieldOne,updateTextFieldTwo;Button addButton, deleteButton, retrieveButton, updateButton; TableLayout dataTable; AABDatabaseManager db; @Override public void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); setContentView(R.layout.main); db = new AABDatabaseManager(this); setupViews(); addButtonListeners(); updateTable(); } catch (Exception e) { Log.e("ERROR", e.toString()); e.printStackTrace(); } } private void setupViews() { A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  42. 42. dataTable= (TableLayout)findViewById(R.id.data_table); textFieldOne= (EditText)findViewById(R.id.text_field_one); textFieldTwo= (EditText)findViewById(R.id.text_field_two); idField= (EditText)findViewById(R.id.id_field); updateIDField=(EditText)findViewById(R.id.update_id_field); updateTextFieldOne= (EditText)findViewById(R.id.update_text_field_one); updateTextFieldTwo= (EditText)findViewById(R.id.update_text_field_two); addButton = (Button)findViewById(R.id.add_button); deleteButton = (Button)findViewById(R.id.delete_button); retrieveButton =(Button)findViewById(R.id.retrieve_button); updateButton = (Button)findViewById(R.id.update_button);}private void addButtonListeners(){ addButton.setOnClickListener ( new View.OnClickListener() { @Override public void onClick(View v) {addRow();} } ); deleteButton.setOnClickListener ( new View.OnClickListener() { @Override public void onClick(View v) {deleteRow();} } ); updateButton.setOnClickListener ( new View.OnClickListener() A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  43. 43. { @Override public void onClick(View v) {updateRow();} } ); retrieveButton.setOnClickListener ( new View.OnClickListener() { @Override public void onClick(View v) {retrieveRow();} } );}private void addRow(){ try { // ask the database manager to add a row given the two strings db.addRow ( textFieldOne.getText().toString(), textFieldTwo.getText().toString() ); // request the table be updated updateTable(); // remove all user input from the Activity emptyFormFields(); } catch (Exception e) { Log.e("Add Error", e.toString()); A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  44. 44. e.printStackTrace(); }}private void deleteRow(){ try { // ask the database manager to delete the row with the give rowID. db.deleteRow(Long.parseLong(idField.getText().toString())); // request the table be updated updateTable(); // remove all user input from the Activity emptyFormFields(); } catch (Exception e) { Log.e("Delete Error", e.toString()); e.printStackTrace(); }}private void retrieveRow(){ try { // The ArrayList that holds the row data ArrayList<Object> row; // ask the database manager to retrieve the row with the given rowID row = db.getRowAsArray(Long.parseLong(updateIDField.getText().toString())); // update the form fields to hold the retrieved data A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  45. 45. updateTextFieldOne.setText((String)row.get(1)); updateTextFieldTwo.setText((String)row.get(2)); } catch (Exception e) { Log.e("Retrieve Error", e.toString()); e.printStackTrace(); }}private void updateRow(){ try { db.updateRow ( Long.parseLong(updateIDField.getText().toString()), updateTextFieldOne.getText().toString(), updateTextFieldTwo.getText().toString() ); updateTable(); emptyFormFields(); } catch (Exception e) { Log.e("Update Error", e.toString()); e.printStackTrace(); }}private void emptyFormFields(){ textFieldOne.setText(""); textFieldTwo.setText(""); idField.setText(""); updateIDField.setText(""); A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  46. 46. updateTextFieldOne.setText(""); updateTextFieldTwo.setText(""); } private void updateTable() { while (dataTable.getChildCount() > 1) { dataTable.removeViewAt(1); } ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays(); for (int position=0; position < data.size(); position++) { TableRow tableRow= new TableRow(this); ArrayList<Object> row = data.get(position); TextView idText = new TextView(this); idText.setText(row.get(0).toString()); tableRow.addView(idText); TextView textOne = new TextView(this); textOne.setText(row.get(1).toString()); tableRow.addView(textOne); TextView textTwo = new TextView(this); textTwo.setText(row.get(2).toString()); tableRow.addView(textTwo); dataTable.addView(tableRow); } }} A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

×