Saving Contact into a custom database

We have learned about the ListView to display a list that allows multiple selections from the users. Next, we learned how to extract the contacts from our phone book and link this results to the ListView. If you have not yet done that, you may want to go back to learn these stuffs first, by clicking on the links: basic tutorial on ListView and Extract Contacts from Phone.

In this post, we will go next step - to save the user's selection into our database so that the user's selections can be used for other purposes. To do this, we will need to touch on the topic of SQLiteDatabase. For theory, you may want to refer to any books or online resources. Basically, SQLiteDatabase is similar to SQL Database except that it has less functions and powers. For details, you may refer to those resources.

To start with this, firstly, we create a database helper class because we do not want to see our main source codes with SQL stuffs. It is for better organization of codes and we think it is cleaner in a sense. To do it, you will need to create a new file under the package. You got to name it as "DataHelper.java". Below is the code for that class.

package edu.mobilestudent.saveRecordtoDatabase;

import java.util.ArrayList;
import java.util.List;

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

/*DataHelper is a class to support for 
all the database-related activities.*/
public class DataHelper{
 private static final String DATABASE_NAME = "myDB.db";
 private static final int DATABASE_VERSION = 1;
 private static final String TABLE_NAME = "whitelist";
 
 private Context context;
 private SQLiteDatabase db;
 
 private SQLiteStatement insertStmt;
 private static final String INSERT = "insert into "+
TABLE_NAME+"(name) values (?)";
 //Constructor for DataHelper
 public DataHelper(Context context){
  this.context = context;
  OpenHelper openHelper = new OpenHelper(this.context);
  this.db = openHelper.getWritableDatabase();
  this.insertStmt = this.db.compileStatement(INSERT);
 }
 
 //Insert into table
 public long insert(String name){
  this.insertStmt.bindString(1, name);
  return this.insertStmt.executeInsert();
 }
 
 //Clear table
 public void deleteAll(){
  this.db.delete(TABLE_NAME, null, null);
 }
 
 //Get List
 public List selectAll(){
  List list = new ArrayList();
  Cursor cursor = this.db.query(TABLE_NAME, new String[] {"name"}, null, 
  null, null, null, "name desc");
  if (cursor.moveToFirst()){
   do{
    list.add(cursor.getString(0));
   }while (cursor.moveToNext());
  }
  if (cursor != null && !cursor.isClosed()){
   cursor.close();
  }
  return list;
 }
 
 private static class OpenHelper extends SQLiteOpenHelper{
  OpenHelper(Context context){
   super(context,DATABASE_NAME,null,DATABASE_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
   db.execSQL("CREATE TABLE "+TABLE_NAME+
   "(id INTEGER PRIMARY KEY, name TEXT)");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   Log.w("TEST", "Upgrading database, this will drop and recreate.");
   db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
   onCreate(db);
  }
 }
}


Now, we will use back our old layout as our previous examples. So, the "main.xml" will look like this:










It is also to take note that your "androidmanifest.xml" has the uses-permission for the phone read. Alright! Now, your main source code will be implemented as below. Basically, you will add in the DataHelper class to help you with the insertion of new records and deletion of records.

package edu.mobilestudent.saveRecordtoDatabase;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SaveRecordtoDatabaseActivity extends Activity {
 private TextView selection;
 private ListView iView;
 private DataHelper dh;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //namesList is to hold all the extracted names from phone book
        ArrayList namesList = new ArrayList();
        ContentResolver cr = getContentResolver(); //to communicate to phone book        
        Cursor pc= cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        pc.moveToFirst();
        while (pc.isAfterLast()==false){
         String name=pc.getString(pc.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
         namesList.add(name);
         pc.moveToNext();
        }
        
        //Copy the arrayList into Array
        final String[] mString=(String[])namesList.toArray(new String[namesList.size()]);

        //Communicate to layout by definition
        iView=(ListView)findViewById(R.id.list);
        selection=(TextView)findViewById(R.id.selection);
        
        //Call for database helper
        dh = new DataHelper(this);
        
        //Copy the array into ListView with option - multiple selections
        iView.setAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_multiple_choice,mString));
        iView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        
        //Event triggered upon selection
        iView.setOnItemClickListener(new OnItemClickListener(){
         @Override
         public void onItemClick(AdapterView parent, View v, int pos, long id) {
          selection.setText("");
          dh.deleteAll();
          
          int len = iView.getCount();
          SparseBooleanArray checked = iView.getCheckedItemPositions();
          for (int i=0; i<len; i++){
           if (checked.valueAt(i)) {
            selection.append(mString[checked.keyAt(i)]+" ");
            dh.insert(mString[checked.keyAt(i)]);
           }
          }    
         }
        });
    }
}


Now, this is the result of what you have done. Select a few of contacts and it will be written to your database.



To see your database, you will need to use your adb shell to view the result. The adb shell is the program that is available in your Android SDK folder, under "platform tools". Use your command prompt to go to that folder.

Type command: "adb -e shell". You will be prompted to shell environment. Once you are in shell environment, use "ls" to list all directories and "cd" to change the current directory. Change to "data/data//databases". Once you are there, follow the codes below:

# sqlite3 myDB.db
SQLite version 3.5.9
Enter ".help" for instructions
sqlite> select * from whitelist;
select * from whitelist;
1|Ngee Ann
2|Singapore
sqlite>