How to Access Contacts In Android
In this blog I will describe how to access or read Conatcts/Phonebook in your Android Application.
Contacts are stored in separate tables(in Row and Column form)
ContactsContract
ContactsContract defines an extensible database of contact-related
information. Contact information is stored in a three-tier data model:
-
A row in the
ContactsContract.Data
table can store any kind of personal data, such
as a phone number or email addresses. The set of data kinds that can be
stored in this table is open-ended. There is a predefined set of common
kinds, but any application can add its own data kinds.
-
A row in the
ContactsContract.RawContacts
table represents a set of data describing a
person and associated with a single account (for example, one of the user's
Gmail accounts).
-
A row in the
ContactsContract.Contacts
table represents an aggregate of one or more
RawContacts presumably describing the same person. When data in or associated with
the RawContacts table is changed, the affected aggregate contacts are updated as
necessary.
find more Information here
Here variable
personName will contain the name and
number will contain the phone number of the Contact
Code to read/access the contacts
Cursor c1;
// list Columns to retive , pass null to get all the columns
String col[]={ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME};
c1 =
getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, col,
null, null, ContactsContract.Contacts.DISPLAY_NAME);
String personName = null, number = "";
if(c1==null)
return;
// Fetch the Corresponding Phone Number of Person Name
try
{
if(c1.getCount() > 0)
{
while(c1.moveToNext())
{
String id = c1.getString(c1.getColumnIndex(Contacts._ID));
personName = c1.getString(c1.getColumnIndex(Contacts.DISPLAY_NAME));
if(id==null||personName==null)
continue;
Cursor cur =
mContext.getContentResolver().query(CommonDataKinds.Phone.CONTENT_URI,
null, CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
if(cur==null)
continue;
number = "";
while(cur.moveToNext())
{
number = cur.getString(cur.getColumnIndex(CommonDataKinds.Phone.NUMBER));
}
cur.close();
}
}
}
catch(Exception e)
{
}
finally
{
c1.close();
}
Working With Database in Android
In this Post I will discuss about creating your own database and
writing functions for Insertion, Deletion and Updation of Data in
Table.
DataBaseHelper:
We will use
SQLiteOpenHelper class and extend this class
and overside the methods onCreate, onUpgrade
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper (Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
@Override
public void onCreate(SQLiteDatabase _db)
{
// statement to create the Table
_db.execSQL(SMSBlockerDataBaseAdapter.DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version "
+_oldVersion + " to " +_newVersion + ", which will destroy all old
data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "SMSTABLE");
// Create a new one.
onCreate(_db);
}
}
SMSBlockerDataBaseAdapter
We create a DataBaseAdpater class and write the functions for following tasks
- to Open the database
- to close the database
- to insert a new Row/Record in Database
- to delete one or more Records in Database
- to update the database
In the example Code given below I have created a Table to store SMSes with following Columns
Id: Primary Key of the Table
Sender Name: Name of SMS Sender
Sender Number: Phone Number of the Sender
Time: date and time (In Miliseconds) at which SMS is received
Inserting a new Record in table
To Insert a new Record in Table we need to create an Object of ContentValues class and put the Values in this like:
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("COLUMN_NAME1", values);
newValues.put("COLUMN_NAME2", values);
and so on
then
// Insert the row into your table
db.insert("TABLENAME", null, newValues);
Deleting a Record from Table
we can delete a row from the Table with delete method
delete("TABLE ANME",String where, String[] valuesForWhere)
for Ex:
String where="ID=?";
int numberOFEntriesDeleted= db.delete("BLOCKEDSMSTABLE", where, new String[]{ID}) ;
will delete the Record containing IDs in new String[]{ID} array.
To get All the Record in the Table
public Cursor getAllEntries ()
{
return db.query("BLOCKEDSMSTABLE", null,null, null, null, null, "TIME DESC");
}
TIME DESC will fetch in
descending order of Time , Pass null to fetch in Ascending Order because
by Deafault it fetches in ascending Order
To get 1 or more records depending on Some Condition
Task task=new Task();
Cursor cursor=db.query("BLOCKEDSMSTABLE", null, " ID=?", new String[]{ID}, null, null, null);
"ID=?" at RunTime ? will be replaced by string in the Array OF String passed as 4th parameter
the above query will fetch all the records containing the IDs in String Array(4th parameter)
Updating The Table
Updating is little similar to Inserting a record in Table
to update the table we need to create an Object of ContentValues and put the new Values in ContentValues object
ContentValues updatedValues = new ContentValues();
// Assign new values for each row.
updatedValues.put("TIME", taskToBeUpdated.time);
updatedValues.put("MESSAGE",taskToBeUpdated.message);
updatedValues.put("RECIPIENTNUMBER",taskToBeUpdated.recipientNumber);
updatedValues.put("RECIPIENTNAME", taskToBeUpdated.recipientName);
String where="ID = ?";
db.update("SMSTABLE",updatedValues, where, new String[]{ID});
You can Modify the where variable as per your requirement like where "EMP_ID=" etc.
How to use this DataBaseAdapter Class in Activities
Create an Instance of DataBaseAdapter
Open the DataAbse
Call the Functions/Methods
See The Code :
SMSSchedulerDataBaseAdapter smsSchedulerDataBaseAdapter =new SMSSchedulerDataBaseAdapter(this);
smsSchedulerDataBaseAdapter=smsSchedulerDataBaseAdapter.open();
smsSchedulerDataBaseAdapter.insertEntry(yourParameter);
smsSchedulerDataBaseAdapter.getAllEntries();
The Complete Code :
public class SMSBlockerDataBaseAdapter
{
// Name of the database
static final String DATABASE_NAME = "SMSBLOCKERDATABASE.db";
// database version if creating first time it should be 1
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table BLOCKEDSMSTABLE " +
"( " +"ID integer primary key
autoincrement,MESSAGE text, SENDERNUMBER text, SENDERNAME text, TIME
integer ); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public SMSBlockerDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Open the Database
public SMSBlockerDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
// Close the Database
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
// to Insert A record in Table
public void insertEntry(Task taskToInsert)
{
// TODO: Create a new ContentValues to represent the row
// and insert it into the database.
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("MESSAGE", taskToInsert.message);
newValues.put("SENDERNUMBER",taskToInsert.senderNumber);
newValues.put("SENDERNAME", taskToInsert.senderName);
newValues.put("TIME",taskToInsert.time);
// Insert the row into your table
db.insert("BLOCKEDSMSTABLE", null, newValues);
}
public int deleteEntry(String ID)
{
String where="ID=?";
int numberOFEntriesDeleted= db.delete("BLOCKEDSMSTABLE", where, new String[]{ID}) ;
return numberOFEntriesDeleted;
}
public void deleteOlderEntries()
{
String olderTime=String.valueOf(new GregorianCalendar().getTimeInMillis()-7*24*60*60*1000);
String where="TIME < ?";
int numberOFEntriesDeleted= db.delete("BLOCKEDSMSTABLE", where, new String[]{olderTime}) ;
Toast.makeText(context, "Number Of Entries Deleted "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
}
public Cursor getAllEntries ()
{
return db.query("BLOCKEDSMSTABLE", null,null, null, null, null, "TIME DESC");
}
public Task getSinlgeEntry(String ID)
{
Task task=new Task();
Cursor cursor=db.query("BLOCKEDSMSTABLE", null, " ID=?", new String[]{ID}, null, null, null);
if(cursor.getCount()==0)
{
return null;
}
cursor.moveToFirst();
task.id= cursor.getString(cursor.getColumnIndex("ID"));
task.message = cursor.getString(cursor.getColumnIndex("MESSAGE"));
task.senderNumber = cursor.getString(cursor.getColumnIndex("SENDERNUMBER"));
task.senderName = cursor.getString(cursor.getColumnIndex("SENDERNAME"));
task.time = Long.parseLong(cursor.getString(cursor.getColumnIndex("TIME")));
task.reason=cursor.getString(cursor.getColumnIndex("REASON"));
//Log.i("getSingle Entry ID: "+"PhoneNumber "+task.senderName+" "+task.message,ID);
cursor.close();
return task;
}
}