I have jokes.db database. This database file imported from using this article., http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/. Now i have Jokes.db in to /data/data/a.b.c/database/Jokes.db. In this database , I have two table NepaliJokes and EnglishJokes. So Now I want to retrive this nepali and english jokes and display in to textview, But I have done following code but couldnot more idea behind How to retrieve data from database.
public class FunnyJokes extends Activity implements View.OnClickListener {
private SQLiteDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
Button back;
super.onCreate(savedInstanceState);
setContentView(R.layout.displayjoks1);
back = (Button) findViewById(R.id.back_btn);
back.setOnClickListener(this);
DataBaseHelper helper = new DataBaseHelper(this);
database = helper.getWritableDatabase();
loadJokes();
}
private void loadJokes() {
//jok=new ArrayList<String>();
/*Cursor c = database.query("SELECT title,body" +
" FROM " + 'tableName'
+ " WHERE category=1;",
null);*/
Cursor c = database.query("NepaliJokes",
null, null, null, null, null, null);
c.moveToPosition(0);
TextView tv= (TextView) findViewById(R.id.textView1);
tv.append(c.getString(1));
c.close();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.back_btn:
FunnyJokes.this.finish();
break;
default:
break;
}
}
}
I also use the database file import from in DDMS->fileExploer. I import database file Pull mobile icon from left of file explorer section.
To read values from the table:
Create a cursor to read data from the database.
Write the following function.
public Cursor retrieveRecords(int category)
{
Cursor c = null;
c = db.rawQuery("select title,body from tablename where category=" +category, null);
return c;
}
Now get the values from the cursor.
public void getDataFromDatabase()
{
try
{
Cursor cursor = null;
db.OpenDatabase();
cursor = db.retrieveRecords();
if (cursor.getCount() != 0)
{
if (cursor.moveToFirst())
{
do
{
titleArrayList.add(cursor.getString(cursor.getColumnIndex("title")));
bodyArrayList.add(cursor.getString(cursor.getColumnIndex("body")));
} while (cursor.moveToNext());
}
db.closeDatabase();
}
cursor.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
I an using the fallowing class for manage DataBase in my application.
public class PersonDbHelper {
public class Row_DocumentTable extends Object {
public int rwo_id;
public String dockey;
public String docid;
public String size;
public String status;
public String name;
public String product_discription;
public String type;
public String publisher;
public String version;
public String filepathurl;
public String basepage;
public String copypaste;
public String save;
public String print;
public String printablepage;
public String nonprintablepage;
public String search;
public String watermarkimageurl;
public String expiry;
public String versiondescription;
public String update_available;
public String localfilepath;
}
public class Row_CategoriesTable extends Object {
public String dockey;
public String category_id;
public String category_name;
}
private static final String DROP_DOCUMENTDETAIL_TABLE_FROM_DATABASE = "drop table if exists CONTENTRAVENDB.DOCUMENTDETAIL";
private static final String DROP_CATEGORIES_TABLE_FROM_DATABASE = "drop table if exists CONTENTRAVENDB.CATEGORIES";
private static final String DATABASE_CREATE_DOCUMENTDETAIL = "create table DOCUMENTDETAIL(row_id integer primary key autoincrement, dockey text , "
+ "docid text not null,"
+ "size text not null,"
+ "status text not null,"
+ "name text not null,"
+ "product_discription text not null,"
+ "type text not null,"
+ "publisher text not null,"
+ "version text not null,"
+ "filepathurl text not null,"
+ "basepage text not null,"
+ "copypaste text not null,"
+ "save text not null,"
+ "print text not null,"
+ "printablepage text not null,"
+ "nonprintablepage text not null,"
+ "search text ,"
+ "watermarkimageurl text not null,"
+ "expiry text not null,"
+ "versiondescription text not null,"
+ "update_available text not null,"
+ "localfilepath text not null"
+ ");";
private static final String DATABASE_CREATE_CATEGORIES = "create table CATEGORIES(_id integer primary key autoincrement, "
+ "dockey text ,"
+ "category_id text ,"
+ "category_name text"
+ ");";
private static final String DATABASE_NAME = "CONTENTRAVENDB";
private static final String DATABASE_TABLE1 = "CATEGORIES";
private static final String DATABASE_TABLE2 = "DOCUMENTDETAIL";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase db;
public PersonDbHelper(Context ctx) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
db.execSQL(DATABASE_CREATE_DOCUMENTDETAIL);
db.execSQL(DATABASE_CREATE_CATEGORIES);
}
public void dropAllTable(Context ctx) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
// db.execSQL(DROP_DOCUMENTDETAIL_TABLE_FROM_DATABASE);
// db.execSQL(DROP_CATEGORIES_TABLE_FROM_DATABASE);
db.delete(DATABASE_TABLE1, null, null);
db.delete(DATABASE_TABLE2, null, null);
close();
}
public PersonDbHelper(Context ctx, String abc) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
}
public PersonDbHelper() {
}
public void close() {
db.close();
}
public void createRow_InDocumentDetailTable(String dockey, String docid,
String size, String status, String name,
String product_discription, String type, String publisher,
String version, String filepathurl, String basepage,
String copypaste, String save, String print, String printablepage,
String nonprintablepage, String search, String watermarkimageurl,
String expiry, String versiondescription, String update_available,
String localfilepath) {
ContentValues initialValues = new ContentValues();
initialValues.put("dockey", dockey);
initialValues.put("docid", docid);
initialValues.put("size", size);
initialValues.put("status", status);
initialValues.put("name", name);
initialValues.put("product_discription", product_discription);
initialValues.put("type", type);
initialValues.put("publisher", publisher);
initialValues.put("version", version);
initialValues.put("filepathurl", filepathurl);
initialValues.put("basepage", basepage);
initialValues.put("copypaste", copypaste);
initialValues.put("save", save);
initialValues.put("print", print);
initialValues.put("printablepage", printablepage);
initialValues.put("nonprintablepage", nonprintablepage);
initialValues.put("search", search);
initialValues.put("watermarkimageurl", watermarkimageurl);
initialValues.put("expiry", expiry);
initialValues.put("versiondescription", versiondescription);
initialValues.put("update_available", update_available);
initialValues.put("localfilepath", localfilepath);
db.insert(DATABASE_TABLE2, null, initialValues);
}
public void createRow_InCategorieTable(String dockey, String category_id,
String category_name) {
ContentValues initialValues = new ContentValues();
initialValues.put("dockey", dockey);
initialValues.put("category_id", category_id);
initialValues.put("category_name", category_name);
db.insert(DATABASE_TABLE1, null, initialValues);
}
public void deleteRow_FromDocumentDetailTable(long rowId) {
db.delete(DATABASE_TABLE2, "_id=" + rowId, null);
}
public List<Row_DocumentTable> fetchAllRows_FromDocumentDetailTable() {
ArrayList<Row_DocumentTable> ret = new ArrayList<Row_DocumentTable>();
try {
String sql = "select * from DOCUMENTDETAIL";
Cursor c = db.rawQuery(sql, null);
// Cursor c =
// db.query(DATABASE_TABLE2, new String[] {
// "row_id","dockey","docid","size", "status", "name",
// "product_discription",
// "type", "publisher", "version", "filepathurl", "basepage"
// , "copypaste", "save", "print", "printablepage",
// "nonprintablepage"
// , "search", "watermarkimageurl", "expiry",
// "versiondescription","update_available","localfilepath"
// }, null, null, null, null, null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Row_DocumentTable row = new Row_DocumentTable();
row.rwo_id = c.getInt(0);
row.dockey = c.getString(1);
row.docid = c.getString(2);
row.size = c.getString(3);
row.status = c.getString(4);
row.name = c.getString(5);
row.product_discription = c.getString(6);
row.type = c.getString(7);
row.publisher = c.getString(8);
row.version = c.getString(9);
row.filepathurl = c.getString(10);
row.basepage = c.getString(11);
row.copypaste = c.getString(12);
row.save = c.getString(13);
row.print = c.getString(14);
row.printablepage = c.getString(15);
row.nonprintablepage = c.getString(16);
row.search = c.getString(17);
row.watermarkimageurl = c.getString(18);
row.expiry = c.getString(19);
row.versiondescription = c.getString(20);
row.update_available = c.getString(21);
row.localfilepath = c.getString(22);
ret.add(row);
c.moveToNext();
}
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return ret;
}
public List<Row_DocumentTable> fetchAllRows_Of_Single_Type(String argtype) {
ArrayList<Row_DocumentTable> ret = new ArrayList<Row_DocumentTable>();
try {
String sql = "select * from DOCUMENTDETAIL where type='" + argtype
+ "'";
Cursor c = db.rawQuery(sql, null);
// Cursor c=db.query(DATABASE_TABLE2, new String[] {
// "dockey","docid", "status", "name", "product_discription",
// "type", "publisher", "version", "filepathurl", "basepage"
// , "copypaste", "save", "print", "printablepage",
// "nonprintablepage"
// , "search", "watermarkimageurl", "expiry", "versiondescription"
// }, "type=PDF", null, null, null, null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Row_DocumentTable row = new Row_DocumentTable();
row.rwo_id = c.getInt(0);
row.dockey = c.getString(1);
row.docid = c.getString(2);
row.size = c.getString(3);
row.status = c.getString(4);
row.name = c.getString(5);
row.product_discription = c.getString(6);
row.type = c.getString(7);
row.publisher = c.getString(8);
row.version = c.getString(9);
row.filepathurl = c.getString(10);
row.basepage = c.getString(11);
row.copypaste = c.getString(12);
row.save = c.getString(13);
row.print = c.getString(14);
row.printablepage = c.getString(15);
row.nonprintablepage = c.getString(16);
row.search = c.getString(17);
row.watermarkimageurl = c.getString(18);
row.expiry = c.getString(19);
row.versiondescription = c.getString(20);
row.update_available = c.getString(21);
ret.add(row);
c.moveToNext();
}
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return ret;
}
public List<Row_CategoriesTable> fetchAllRows_FromCategorieTable(
String argsql) {
ArrayList<Row_CategoriesTable> ret = new ArrayList<Row_CategoriesTable>();
try {
String sql = argsql;
Cursor c = db.rawQuery(sql, null);
// Cursor c =
// db.query(true,DATABASE_TABLE1, new String[] {
// "dockey","category_id","category_name"
// }, null,null,null, null, null,null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Row_CategoriesTable row = new Row_CategoriesTable();
row.dockey = c.getString(0);
row.category_id = c.getString(0);
row.category_name = c.getString(0);
ret.add(row);
c.moveToNext();
}
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return ret;
}
public Row_DocumentTable fetchRow_FromDocumentDetailTableByDocKey(
String dockey) {
Row_DocumentTable row = new Row_DocumentTable();
String sql = "select * from DOCUMENTDETAIL where dockey='" + dockey
+ "'";
try {
Cursor c = db.rawQuery(sql, null);
// Cursor c =
// db.query(DATABASE_TABLE2, new String[] {
// "dockey","docid", "status", "name", "product_discription",
// "type", "publisher", "version", "filepathurl", "basepage"
// , "copypaste", "save", "print", "printablepage",
// "nonprintablepage"
// , "search", "watermarkimageurl", "expiry", "versiondescription"},
// "dockey=" + dockey, null, null,
// null,null,"name desc");
if (c.getCount() > 0) {
c.moveToFirst();
row.rwo_id = c.getInt(0);
row.dockey = c.getString(1);
row.docid = c.getString(2);
row.size = c.getString(3);
row.status = c.getString(4);
row.name = c.getString(5);
row.product_discription = c.getString(6);
row.type = c.getString(7);
row.publisher = c.getString(8);
row.version = c.getString(9);
row.filepathurl = c.getString(10);
row.basepage = c.getString(11);
row.copypaste = c.getString(12);
row.save = c.getString(13);
row.print = c.getString(14);
row.printablepage = c.getString(15);
row.nonprintablepage = c.getString(16);
row.search = c.getString(17);
row.watermarkimageurl = c.getString(18);
row.expiry = c.getString(19);
row.versiondescription = c.getString(20);
row.update_available = c.getString(21);
row.localfilepath = c.getString(22);
return row;
} else {
row.docid = null;
row.dockey = row.name = null;
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
return row;
}
public void updateRow_InDocumentDetailTableByDocKey(String dockey,
String docid, String status, String name,
String product_discription, String type, String publisher,
String version, String filepathurl, String basepage,
String copypaste, String save, String print, String printablepage,
String nonprintablepage, String search, String watermarkimageurl,
String expiry, String versiondescription, String update_available) {
ContentValues args = new ContentValues();
args.put("dockey", dockey);
args.put("docid", docid);
args.put("status", status);
args.put("name", name);
args.put("product_discription", product_discription);
args.put("type", type);
args.put("publisher", publisher);
args.put("version", version);
args.put("filepathurl", filepathurl);
args.put("basepage", basepage);
args.put("copypaste", copypaste);
args.put("save", save);
args.put("print", print);
args.put("printablepage", printablepage);
args.put("nonprintablepage", nonprintablepage);
args.put("search", search);
args.put("watermarkimageurl", watermarkimageurl);
args.put("expiry", expiry);
args.put("versiondescription", versiondescription);
args.put("update_available", update_available);
db.update(DATABASE_TABLE2, args, "dockey='" + dockey + "'", null);
}
public Cursor GetAllRows() {
try {
return db.query(DATABASE_TABLE2, new String[] { "dockey", "docid",
"status", "name", "product_discription", "type",
"publisher", "version", "filepathurl", "basepage",
"copypaste", "save", "print", "printablepage",
"nonprintablepage", "search", "watermarkimageurl",
"expiry", "versiondescription" }, null, null, null, null,
null);
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
return null;
}
}
public void updateRow_InDocumentDetailTableByDocKey_UpdateAvl(Context ctx,
String dockey, String update_available) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
ContentValues args = new ContentValues();
args.put("update_available", update_available);
db.update(DATABASE_TABLE2, args, "dockey='" + dockey + "'", null);
}
public void updateRow_InDocumentDetailTableByDocKey_LocalFilePath(
Context ctx, String dockey, String argLocalFilePath) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
ContentValues args = new ContentValues();
args.put("localfilepath", argLocalFilePath);
db.update(DATABASE_TABLE2, args, "dockey='" + dockey + "'", null);
}
}
I have two table and apply all the query insert update delete and createtable select using the code it is working fine.
I hope this is help.
First of all don't use tv.append instead use setText because if u use append then ur next joke will be append to the previous one and textView show the jokes as you click the button
Actually the answere is long enough so
I have written a ansere in my blog please see the link the code will do exactly what you are lokking for but i just made one table you can add more table similarly.
You can visit HERE
Related
I am building an SQLite DB. One of the tables consists of 2 columns - term and definition.
My question is : How can I query the DB, in order the pair term-definition to be returned in order to be able to insert the data in the activity after that (the term and data are in ExpandableListView, the term is the Key, the data - the value).
Here is the code of the data source so far:
public class TermDataSource extends DAO {
//constants
public static final String TABLE_NAME = "terms";
public static final String TERM = "term";
public static final String DEFINITION = "definition";
//columns in the table
public static final int FIELD_ID_ID = 0;
public static final int FIELD_ID_TERM = 1;
public static final int FIELD_ID_DEFINITION = 2;
public TermDataSource (Context context){
super(context);
}
private String [] selectFields = {_ID, TERM, DEFINITION};
public Cursor getTermsData(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, selectFields, null, null, null, null, null);
return cursor;
}
public List<Term> getTerms(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, selectFields, null, null, null, null, null);
List<Term> terms = new ArrayList<Term>();
if(cursor!=null){
Term term = null;
while(cursor.moveToNext()){
term = getTermFromCursor(cursor);
terms.add(term);
}
cursor.close();
}
db.close();
return terms;
}
private Term getTermFromCursor (Cursor cursor){
Term term = new Term();
term.setTermId(cursor.getInt(FIELD_ID_ID));
term.setTerm(cursor.getString(FIELD_ID_TERM));
term.setDefinition(cursor.getString(FIELD_ID_DEFINITION));
return term;
}
}
Create a folder res>raw and put youfile.csv in that folder.
Use this method to insert data in Your Database from CSV file.
public void insertCSVData(Activity activity, InputStream is, String tableName) {
String colunmNames = null, str1 = null;
open();
try {
BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
String line = "";
String str2 = ");";
db.beginTransaction();
int i = 0;
while ((line = buffer.readLine()) != null) {
i++;
if (i == 1) {
colunmNames = line;
str1 = "INSERT INTO " + tableName + " (" + colunmNames + ") values (";
} else {
StringBuilder sb = new StringBuilder(str1);
String[] str = line.split(",");
for (int h = 0; h < str.length; h++) {
if (h == str.length - 1) {
sb.append("'" + str[h] + "'");
} else {
sb.append("'" + str[h] + "',");
}
}
sb.append(str2);
db.execSQL(sb.toString());
}
}
db.setTransactionSuccessful();
db.endTransaction();
} catch (Exception e) {
close();
e.printStackTrace();
}
close();
}
Call this method by the below code :
insertCSVData(Activity.this, getResources().openRawResource(R.raw.yourfile),"Your Table Name");
How I can get a different values from a column with the same name (like the photo)?
In the photo, "test" have a 3 differents values, how I can load them to a ListView or a Spinner?
I have this code, works, but don't get the 3 values, only first value:
MainActivity
public void lookupProduct (View view) {
DatabaseHandler dbHandler = new DatabaseHandler(getApplicationContext());
Name name = dbHandler.findProduct(spinner.getSelectedItem().toString());
Toast.makeText(this, spinner.getSelectedItem().toString(), Toast.LENGTH_LONG).show();
Intent j = new Intent(view.getContext(), SubActivity.class);
Bundle dados = new Bundle();
if (name != null) {
inputLabel.setText(String.valueOf(name.getName()));
values.setText(String.valueOf(name.getValue()));
// Passar para SubActivity
dados.putString("name", String.valueOf(name.getName()));
dados.putString("value", String.valueOf(name.getValue()));
} else {
inputLabel.setText("No Match Found");
dados.putString("name","No Match Found" );
dados.putString("value", "No Match Found");
}
j.putExtras(dados);
startActivity(j);
}
DatabaseHelper
public Name findProduct(String name) {
String query = "Select * FROM " + TABLE_LABELS + " WHERE " + KEY_NAME + " = \"" + name + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Name names = new Name();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
names.setID(Integer.parseInt(cursor.getString(0)));
names.setName(cursor.getString(1));
names.setValue(cursor.getString(2));
cursor.close();
} else {
names = null;
}
db.close();
return names;
}
NameClass
public class Name {
private int _id;
private String _name;
private String _value;
public Name() {
}
public Name(int id, String name, String value) {
this._id = id;
this._name = name;
this._value = value;
}
public Name(String name, String value) {
this._name = name;
this._value = value;
}public String getName() {
return this._name;
}
public String getValue() {
return this._value;
}
Try this
Name names = new Name();
ArrayList<Name > listaName= new ArrayList<>();//create an arraylist of your
custom objects
if (cursor.moveToFirst()) {
do {
names.setID(Integer.parseInt(cursor.getString(0)));
names.setName(cursor.getString(1));
names.setValue(cursor.getString(2));
listaName.add(names);//add your object to arraylist(you were overriding the object.)
} while (cursor.moveToNext());
cursor.close();
//AND ALSO CLOSE DB:
db.close
EDIT 2: Try this and change your --> String Query = "Select * from "+TABLE_NAME;
for ( int i= 1; i< listaName.size(); i++ ) {
System.out.println(listaName.get(i).getName());
}
Your problem:
public Name findProduct(String name) {
String query = "Select * FROM " + TABLE_LABELS + " WHERE " + KEY_NAME + " = \"" + name + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Name names = new Name();
if (cursor.moveToFirst()) {
cursor.moveToFirst(); // this is not necessary because on the top line,
you put it in that position
names.setID(Integer.parseInt(cursor.getString(0)));
names.setName(cursor.getString(1));
names.setValue(cursor.getString(2));
cursor.close(); // You should not close until it is
completely used
} else {
names = null;
}
db.close();
return names;
}
And to read all the cursor is necessary to use a do-while method
If you have any problems, you can ask me again
Though not yet tested, you can try this:
// fetch data from DB
public ArrayList<Name> findProduct(String name) {
String query = "Select * FROM " + TABLE_LABELS + " WHERE " + KEY_NAME + " = \"" + name + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
ArrayList<Name> listOfNames= new ArrayList<>();
if (cursor.moveToFirst()) {
do {
listOfNames.add(new Name(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2)));
} while (cursor.moveToNext());
cursor.close();
db.close
return listOfNames;
}
// add data on spinner
public void addItemsOnSpinner() {
Spinner mSpinner = (Spinner) findViewById(R.id.mSpinner);
ArrayList<String> list = new ArrayList<String>();
for(Name name: findProduct("test")){
list.add(name.getValue());
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(dataAdapter);
}
I'm working on Android 2.0 and am trying to receive a list of all contacts.
Since android.provider.Contacts.People is deprecated, I have to use android.provider.ContactsContract, But I can't find a proper example of how to use it (ex: retrieve a list of all contacts on the phonebook).
Anyone knows where to find such an example?
First, ensure that you have added
<uses-permission android:name="android.permission.READ_CONTACTS"/>
to your AndroidManifest.xml file, then you can loop through your phone contacts like this:
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts._ID));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Boolean.parseBoolean(hasPhone)) {
// You know it has a number so now query it like this
Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
while (emails.moveToNext()) {
// This would allow you get several email addresses
String emailAddress = emails.getString(
emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
}
cursor.close();
Additionally, you can loop through your contacts and simply get the name and phone number like this:
Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while(people.moveToNext()) {
int nameFieldColumnIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String contact = people.getString(nameFieldColumnIndex);
int numberFieldColumnIndex = people.getColumnIndex(PhoneLookup.NUMBER);
String number = people.getString(numberFieldColumnIndex);
}
people.close();
Furthermore, if you need to get things like notes from a contact then you will need to use a different URI, like the following (feel free to use this method):
private String getNote(long contactId) {
String note = null;
String[] columns = new String[] { ContactsContract.CommonDataKinds.Note.NOTE };
String where = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] whereParameters = new String[]{Long.toString(contactId), ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor contacts = getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, where, whereParameters, null);
if (contacts.moveToFirst()) {
rv = contacts.getString(0);
}
contacts.close();
return note;
}
Notice this time I used not only the contact id but the mime type for the query.
Great to see some useful info, it is frustrating how poorly this important topic is covered by docs and such. After too much hacking about I thought I would share a little code also. The following code is a little prettier and get the same thing done more efficiently.
Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
};
String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'";
Cursor contacts = managedQuery(contactUri, PROJECTION, SELECTION, null, null );
The above chunk of code returns a Cursor that points to the resulting query that only contains those rows that have a phone number. This is nice since you typically have many contacts without numbers. Furthermore, the PROJECTION limits the amount of data that is returned.
String key, value, phoneNumber;
Hashtable contactPhoneInfo = new Hashtable<String, String>();
Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String [] PHONES_PROJECTION = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };
String PHONE_SELECTION = null;
contacts.moveToFirst();
do{
long contactId = contacts.getLong(idColumnIndex);
PHONE_SELECTION = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId;
Cursor phones = managedQuery(phoneUri,
PHONES_PROJECTION,
null,
null,
ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY + " DESC");
phones.moveToFirst();
key = phones.getString(0).replaceAll("\\D", "");
value = contacts.getString(nameColumnIndex);
contactPhoneInfo.put(key, value);
}while(contacts.moveToNext());
contacts.close();
}
The above chunk gets the phone number associated with each contact id that has a phone number. I store all the info in a hash table and with a key value of the phone number. I stripped the phone number of all none digit info also. For some reason even though ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER is valid if you include that in the projection argument it breaks the query, I don't know why and it is frustrating that it does.
The second part of the code above is too slow, all the query calls just bog everything down. The following code is much faster. Just grab all the rows for the phone content and use the contact_ids to sort the data you want.
Cursor phones = managedQuery(phoneUri,
PHONES_PROJECTION,
PHONE_SELECTION,
null,
ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY + " DESC");
contacts.moveToFirst();
do{
value = "";
key = contacts.getString(idColumnIndex);
contactPhoneInfo.put(key, value);
}while(contacts.moveToNext());
phones.moveToFirst();
Set keySet = contactPhoneInfo.keySet();
idColumnIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
int numColumnIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
do{
key = phones.getString(idColumnIndex);
if(keySet.contains(key)){
value = phones.getString(numColumnIndex).replaceAll("\\D", "");
contactPhoneInfo.put(key, value);
}
}while(phones.moveToNext());
You end up with a hashtable with all the info you want in it. Of course you could put whatever info you want into the data structure. The second way of doing it is much much faster.
Just want to add, when you are retrieving the contacts you might get a lot of "garbage" contacts - for example some email addresses that a user has at some point send an email to, but are not aggregated... If you want only the contacts visible to the user, as in the Androids own contacts application you need to restrict the selection to only IN_VISIBLE_GROUP.
String where = ContactsContract.Contacts.IN_VISIBLE_GROUP + "= ? ";
String[] selectionArgs = new String[] { "1" };
I think it is important to have the code from this URL http://coderzheaven.com/2011/06/get-all-details-from-contacts-in-android/ on StackOverflow cause at times links like that go down.
public void readContacts(){
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
System.out.println("name : " + name + ", ID : " + id);
// get the phone number
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("phone" + phone);
}
pCur.close();
// get email and type
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
System.out.println("Email " + email + " Email Type : " + emailType);
}
emailCur.close();
// Get note.......
String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] noteWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
if (noteCur.moveToFirst()) {
String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
System.out.println("Note " + note);
}
noteCur.close();
//Get Postal Address....
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
// Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,
// null, null, null, null);
Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, addrWhere, addrWhereParams, null);
while(addrCur.moveToNext()) {
String poBox = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
String street = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String city = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String postalCode = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
String country = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
// Do something with these....
}
addrCur.close();
// Get Instant Messenger.........
String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] imWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE};
Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, imWhere, imWhereParams, null);
if (imCur.moveToFirst()) {
String imName = imCur.getString(
imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
String imType;
imType = imCur.getString(
imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
}
imCur.close();
// Get Organizations.........
String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (orgCur.moveToFirst()) {
String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
}
orgCur.close();
}
}
}
}
emphasized text
I found very easy solution to read contacts. (boring to write code for reading each value so it's good to use wrapper class for contacts)
Of course <uses-permission android:name="android.permission.READ_CONTACTS"/>
ContactList.java
package com.test;
import java.util.ArrayList;
public class ContactList {
private ArrayList<Contact> contacts = new ArrayList<Contact>();
public ArrayList<Contact> getContacts() {
return contacts;
}
public void setContacts(ArrayList<Contact> contacts) {
this.contacts = contacts;
}
public void addContact(Contact contact) {
this.contacts.add(contact);
}
public ContactList() {
}
}
Contact.java
package com.test;
import java.util.ArrayList;
public class Contact {
private String id;
private String displayName;
private ArrayList<Phone> phone;
private ArrayList<Email> email;
private ArrayList<String> notes;
private ArrayList<Address> addresses = new ArrayList<Address>();
private ArrayList<IM> imAddresses;
private Organization organization;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public ArrayList<Phone> getPhone() {
return phone;
}
public void setPhone(ArrayList<Phone> phone) {
this.phone = phone;
}
public void addPhone(Phone phone) {
this.phone.add(phone);
}
public ArrayList<Email> getEmail() {
return email;
}
public void setEmail(ArrayList<Email> email) {
this.email = email;
}
public void addEmail(Email email) {
this.email.add(email);
}
public ArrayList<String> getNotes() {
return notes;
}
public void setNotes(ArrayList<String> notes) {
this.notes = notes;
}
public void AddNotes(String notes){
this.notes.add(notes);
}
public ArrayList<Address> getAddresses() {
return addresses;
}
public void setAddresses(ArrayList<Address> addresses) {
this.addresses = addresses;
}
public void addAddress(Address address) {
this.addresses.add(address);
}
public ArrayList<IM> getImAddresses() {
return imAddresses;
}
public void setImAddresses(ArrayList<IM> imAddresses) {
this.imAddresses = imAddresses;
}
public void addImAddresses(IM imAddr) {
this.imAddresses.add(imAddr);
}
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
}
Address.java
package com.test;
public class Address {
private String poBox;
private String street;
private String city;
private String state;
private String postalCode;
private String country;
private String type;
private String asString = "";
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPoBox() {
return poBox;
}
public void setPoBox(String poBox) {
this.poBox = poBox;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String toString() {
if (this.asString.length() > 0) {
return(this.asString);
} else {
String addr = "";
if (this.getPoBox() != null) {
addr = addr + this.getPoBox() + "n";
}
if (this.getStreet() != null) {
addr = addr + this.getStreet() + "n";
}
if (this.getCity() != null) {
addr = addr + this.getCity() + ", ";
}
if (this.getState() != null) {
addr = addr + this.getState() + " ";
}
if (this.getPostalCode() != null) {
addr = addr + this.getPostalCode() + " ";
}
if (this.getCountry() != null) {
addr = addr + this.getCountry();
}
return(addr);
}
}
public Address(String asString, String type) {
this.asString = asString;
this.type = type;
}
public Address(String poBox, String street, String city, String state,
String postal, String country, String type) {
this.setPoBox(poBox);
this.setStreet(street);
this.setCity(city);
this.setState(state);
this.setPostalCode(postal);
this.setCountry(country);
this.setType(type);
}
}
Email.java
package com.test;
public class Email {
private String address;
private String type;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getType() {
return type;
}
public void setType(String t) {
this.type = t;
}
public Email(String a, String t) {
this.address = a;
this.type = t;
}
}
Im.java
package com.test;
public class IM {
private String name;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public IM(String name, String type) {
this.name = name;
this.type = type;
}
}
Organization.java
package com.test;
public class Organization {
private String organization = "";
private String title = "";
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Organization() {
}
public Organization(String org, String title) {
this.organization = org;
this.title = title;
}
}
Phone.java
package com.test;
public class Phone {
private String number;
private String type;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Phone(String n, String t) {
this.number = n;
this.type = t;
}
}
ContactAPI.java
package com.test;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
public abstract class ContactAPI {
private static ContactAPI api;
public static ContactAPI getAPI() {
if (api == null) {
String apiClass;
if (Integer.parseInt(Build.VERSION.SDK) >= Build.VERSION_CODES.ECLAIR) {
apiClass = "com.*********.ContactAPISdk5";
} else {
apiClass = "com.*********.ContactAPISdk3";
}
try {
Class<? extends ContactAPI> realClass = Class.forName(apiClass).
asSubclass(ContactAPI.class);
api = realClass.newInstance();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return api;
}
public abstract Intent getContactIntent();
public abstract ContactList newContactList();
public abstract Cursor getCur();
public abstract void setCur(Cursor cur);
public abstract ContentResolver getCr();
public abstract void setCr(ContentResolver cr);
}
ContactAPISdk5.java
package com.test;
import java.util.ArrayList;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.provider.ContactsContract;
public class ContactAPISdk5 extends ContactAPI {
private Cursor cur;
private ContentResolver cr;
public Cursor getCur() {
return cur;
}
public void setCur(Cursor cur) {
this.cur = cur;
}
public ContentResolver getCr() {
return cr;
}
public void setCr(ContentResolver cr) {
this.cr = cr;
}
public Intent getContactIntent() {
return(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI));
}
public ContactList newContactList() {
ContactList contacts = new ContactList();
String id;
this.cur = this.cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (this.cur.getCount() > 0) {
while (cur.moveToNext()) {
Contact c = new Contact();
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
c.setId(id);
c.setDisplayName(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
c.setPhone(this.getPhoneNumbers(id));
}
c.setEmail(this.getEmailAddresses(id));
c.setNotes(this.getContactNotes(id));
c.setAddresses(this.getContactAddresses(id));
c.setImAddresses(this.getIM(id));
c.setOrganization(this.getContactOrg(id));
contacts.addContact(c);
}
}
return(contacts);
}
public ArrayList<Phone> getPhoneNumbers(String id) {
ArrayList<Phone> phones = new ArrayList<Phone>();
Cursor pCur = this.cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
phones.add(new Phone(
pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
, pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))
));
}
pCur.close();
return(phones);
}
public ArrayList<Email> getEmailAddresses(String id) {
ArrayList<Email> emails = new ArrayList<Email>();
Cursor emailCur = this.cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
Email e = new Email(emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA))
,emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE))
);
emails.add(e);
}
emailCur.close();
return(emails);
}
public ArrayList<String> getContactNotes(String id) {
ArrayList<String> notes = new ArrayList<String>();
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] whereParameters = new String[]{id,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null);
if (noteCur.moveToFirst()) {
String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
if (note.length() > 0) {
notes.add(note);
}
}
noteCur.close();
return(notes);
}
public ArrayList<Address> getContactAddresses(String id) {
ArrayList<Address> addrList = new ArrayList<Address>();
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] whereParameters = new String[]{id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null);
while(addrCur.moveToNext()) {
String poBox = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
String street = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String city = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String postalCode = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
String country = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
Address a = new Address(poBox, street, city, state, postalCode, country, type);
addrList.add(a);
}
addrCur.close();
return(addrList);
}
public ArrayList<IM> getIM(String id) {
ArrayList<IM> imList = new ArrayList<IM>();
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] whereParameters = new String[]{id,
ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE};
Cursor imCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null);
if (imCur.moveToFirst()) {
String imName = imCur.getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
String imType;
imType = imCur.getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
if (imName.length() > 0) {
IM im = new IM(imName, imType);
imList.add(im);
}
}
imCur.close();
return(imList);
}
public Organization getContactOrg(String id) {
Organization org = new Organization();
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] whereParameters = new String[]{id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null);
if (orgCur.moveToFirst()) {
String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
if (orgName.length() > 0) {
org.setOrganization(orgName);
org.setTitle(title);
}
}
orgCur.close();
return(org);
}
}
ContactAPISdk3.java
package com.test;
import java.util.ArrayList;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.provider.Contacts;
import android.provider.Contacts.People;
public class ContactAPISdk3 extends ContactAPI {
private Cursor cur;
private ContentResolver cr;
public Cursor getCur() {
return cur;
}
public void setCur(Cursor cur) {
this.cur = cur;
}
public ContentResolver getCr() {
return cr;
}
public void setCr(ContentResolver cr) {
this.cr = cr;
}
public Intent getContactIntent() {
return(new Intent(Intent.ACTION_PICK, People.CONTENT_URI));
}
public ContactList newContactList() {
ContactList contacts = new ContactList();
String id="";
this.cur = this.cr.query(People.CONTENT_URI,
null, null, null, null);
if (this.cur.getCount() > 0) {
while (cur.moveToNext()) {
Contact c = new Contact();
id = cur.getString(cur.getColumnIndex(People._ID));
c.setId(id);
c.setDisplayName(cur.getString(cur.getColumnIndex(People.DISPLAY_NAME)));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(People.PRIMARY_PHONE_ID))) > 0) {
c.setPhone(this.getPhoneNumbers(id));
}
c.setEmail(this.getEmailAddresses(id));
ArrayList<String> notes = new ArrayList<String>();
notes.add(cur.getString(cur.getColumnIndex(People.NOTES)));
c.setNotes(notes);
c.setAddresses(this.getContactAddresses(id));
c.setImAddresses(this.getIM(id));
c.setOrganization(this.getContactOrg(id));
contacts.addContact(c);
}
}
return(contacts);
}
public ArrayList<Phone> getPhoneNumbers(String id) {
ArrayList<Phone> phones = new ArrayList<Phone>();
Cursor pCur = this.cr.query(
Contacts.Phones.CONTENT_URI,
null,
Contacts.Phones.PERSON_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
phones.add(new Phone(
pCur.getString(pCur.getColumnIndex(Contacts.Phones.NUMBER))
, pCur.getString(pCur.getColumnIndex(Contacts.Phones.TYPE))
));
}
pCur.close();
return(phones);
}
public ArrayList<Email> getEmailAddresses(String id) {
ArrayList<Email> emails = new ArrayList<Email>();
Cursor emailCur = this.cr.query(
Contacts.ContactMethods.CONTENT_EMAIL_URI,
null,
Contacts.ContactMethods.PERSON_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
Email e = new Email(emailCur.getString(emailCur.getColumnIndex(Contacts.ContactMethods.DATA))
,emailCur.getString(emailCur.getColumnIndex(Contacts.ContactMethods.CONTENT_EMAIL_TYPE))
);
emails.add(e);
}
emailCur.close();
return(emails);
}
public ArrayList<Address> getContactAddresses(String id) {
ArrayList<Address> addrList = new ArrayList<Address>();
String where = Contacts.ContactMethods.PERSON_ID + " = ? AND " + Contacts.ContactMethods.KIND + " = ?";
String[] whereParameters = new String[]{id,
Contacts.ContactMethods.CONTENT_POSTAL_ITEM_TYPE};
Cursor addrCur = this.cr.query(Contacts.ContactMethods.CONTENT_URI, null, where, whereParameters, null);
while(addrCur.moveToNext()) {
String addr = addrCur.getString(addrCur.getColumnIndex(Contacts.ContactMethodsColumns.DATA));
String type = addrCur.getString(addrCur.getColumnIndex(Contacts.ContactMethodsColumns.TYPE));
Address a = new Address(addr, type);
addrList.add(a);
}
addrCur.close();
return(addrList);
}
public ArrayList<IM> getIM(String id) {
ArrayList<IM> imList = new ArrayList<IM>();
String where = Contacts.ContactMethods.PERSON_ID + " = ? AND " + Contacts.ContactMethods.KIND + " = ?";
String[] whereParameters = new String[]{id,
Contacts.ContactMethods.CONTENT_IM_ITEM_TYPE};
Cursor imCur = this.cr.query(Contacts.ContactMethods.CONTENT_URI, null, where, whereParameters, null);
if (imCur.moveToFirst()) {
String imName = imCur.getString(imCur.getColumnIndex(Contacts.ContactMethodsColumns.DATA));
String imType = imCur.getString(imCur.getColumnIndex(Contacts.ContactMethodsColumns.TYPE));
if (imName.length() > 0) {
IM im = new IM(imName, imType);
imList.add(im);
}
}
imCur.close();
return(imList);
}
public Organization getContactOrg(String id) {
Organization org = new Organization();
String where = Contacts.ContactMethods.PERSON_ID + " = ?";
String[] whereParameters = new String[]{id};
Cursor orgCur = this.cr.query(Contacts.Organizations.CONTENT_URI, null, where, whereParameters, null);
if (orgCur.moveToFirst()) {
String orgName = orgCur.getString(orgCur.getColumnIndex(Contacts.Organizations.COMPANY));
String title = orgCur.getString(orgCur.getColumnIndex(Contacts.Organizations.TITLE));
if (orgName.length() > 0) {
org.setOrganization(orgName);
org.setTitle(title);
}
}
orgCur.close();
return(org);
}
}
Note : Don't forget to change package name instead *******.
Source (link can be die any time :))
Put this ....
Cursor phones =
getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String Number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
Let me know if any issue.
This part wouldn't work for me:
while (phones.moveToNext()) {
String phoneNumber = phones.getString(
phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
}
If I use this, though, it does:
while (phones.moveToNext()) {
String pdata = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
Log.v("DATA",pdata);
}
You can use "ContactManager" example from android developer's site
(OR)
Go to the location where you have set the path to download android-sdk in your system. In android-sdk-mac_x86/samples/android-10 folder, you can see "ContactManager" example.
I have tried using this example, worked well in my application.
I'm using Samsung Galaxy Note 4, and I donno why none of the above worked for me.
I mixed up some and made this woking..
Cursor people = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
people.moveToFirst();
while(people.moveToNext()) {
int nameFieldColumnIndex = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String contact = people.getString(nameFieldColumnIndex);
int numberFieldColumnIndex = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);
String number = people.getString(numberFieldColumnIndex);
dbWriter.execSQL("Insert Into ContactsList (ContactName, ContactNumber) Values (" +
"'" + contact.replace("'", "''") + "', '" + number.replace("'", "''") + "')");
}
people.close();
i have a issue making a SQLite edition, basicly, the error is java.lang.NumberFormatException, im making Long.parseLong in my data, but i dont know why the program continues sending me that error , the code of my first class is next:
public class SQLiteActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText ecoursename, etopic, ecourse_description, elength, erating, esearch;
Button insert, view, search, edit, delete;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ecoursename = (EditText) findViewById(R.id.cName);
etopic = (EditText) findViewById(R.id.cTopic);
ecourse_description= (EditText) findViewById(R.id.cDescription);
elength= (EditText) findViewById(R.id.cLength);
erating= (EditText) findViewById(R.id.cRating);
esearch = (EditText) findViewById(R.id.etSearch);
insert = (Button) findViewById(R.id.btInsert);
view = (Button) findViewById(R.id.btView);
search = (Button) findViewById(R.id.btSearch);
edit = (Button) findViewById(R.id.btEdit);
delete = (Button) findViewById(R.id.btDelete);
search.setOnClickListener(this);
edit.setOnClickListener(this);
delete.setOnClickListener(this);
insert.setOnClickListener(this);
view.setOnClickListener(this);
}
public void onClick(View v) {
//TODO Auto-generated method stub
switch (v.getId()){
case R.id.btInsert:
boolean works = true;
try{
String course_name = ecoursename.getText().toString();
String topic = etopic.getText().toString();
String course_description = ecourse_description.getText().toString();
String length = elength.getText().toString();
String rating = erating.getText().toString();
ecoursename.setText("");
etopic.setText("");
ecourse_description.setText("");
elength.setText("");
erating.setText("");
DBAdapter entry = new DBAdapter (SQLiteActivity.this);
entry.open();
entry.createEntry(course_name, topic, course_description, length, rating);
entry.close();
}catch(Exception e){
works = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Dont Works");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}finally{
if(works){
// make click says inserted text
Dialog d = new Dialog(this);
d.setTitle("Works?");
TextView tv = new TextView(this);
tv.setText("is Working");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.btView:
Intent i = new Intent("com.sqlite.base.data.SQLVista");
startActivity(i);
break;
case R.id.btSearch:
String s = esearch.getText().toString();
Long ls = Long.parseLong(s);
DBAdapter dbase= new DBAdapter(this);
try{
dbase.open();
}catch(Exception e){
e.printStackTrace();
}
String bN = dbase.getN(ls);
String bT = dbase.getT(ls);
String bD = dbase.getD(ls);
String bL = dbase.getL(ls);
String bR = dbase.getR(ls);
dbase.close();
ecoursename.setText(bN);
etopic.setText(bT);
ecourse_description.setText(bD);
elength.setText(bL);
erating.setText(bR);
break;
case R.id.btEdit:
try{
String eCo = ecoursename.getText().toString();
String eTo = etopic.getText().toString();
String eDe = ecourse_description.getText().toString();
String eLe = elength.getText().toString();
String eRa = erating.getText().toString();
String eRow = esearch.getText().toString();
long eRowl = Long.parseLong(eRow);
DBAdapter edit = new DBAdapter(this);
edit.open();
edit.edit(eRowl, eCo, eTo, eDe, eLe, eRa);
edit.close();
}catch(Exception e) {
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Dont Works!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
break;
case R.id.btDelete:
break;
}
}
}
my DBAdapter class:
public class DBAdapter {
public static final String ID_ROW = "_id";
public static final String ID_COURSENAME = "course_name";
public static final String ID_TOPIC = "topic";
public static final String ID_DESCRIPTION = "course_description";
public static final String ID_LENGTH = "length";
public static final String ID_RATING = "rating";
private static final String N_DB = "Clases";
private static final String N_TABLE = "Courses";
private static final int VERSION_DB = 1;
private DBHelper nHelper;
private final Context nContext;
private SQLiteDatabase nDB;
private static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context, N_DB, null, VERSION_DB);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(" CREATE TABLE " + N_TABLE + "(" + ID_ROW + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ID_COURSENAME + " TEXT NOT NULL, " + ID_TOPIC + " TEXT NOT NULL, " + ID_DESCRIPTION + " TEXT NOT NULL, " + ID_LENGTH + " TEXT NOT NULL, " + ID_RATING + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + N_TABLE);
onCreate(db);
}
}
public DBAdapter (Context c){
nContext = c;
}
public DBAdapter open() throws SQLException{
nHelper = new DBHelper(nContext);
nDB = nHelper.getWritableDatabase();
return this;
}
public void close() {
// TODO Auto-generated method stub
nHelper.close();
}
public long createEntry(String course_name, String topic, String course_description, String length, String rating ) {
// TODO Auto-generated method stub
//insert data
ContentValues cv = new ContentValues();
cv.put(ID_COURSENAME, course_name);
cv.put(ID_TOPIC, topic);
cv.put(ID_DESCRIPTION, course_description);
cv.put(ID_LENGTH, length);
cv.put(ID_RATING, rating);
//return content in table
return nDB.insert(N_TABLE, null, cv);
}
public String receive() {
// TODO Auto-generated method stub
String[] columns = new String[]{ID_ROW, ID_COURSENAME, ID_TOPIC, ID_DESCRIPTION, ID_LENGTH, ID_RATING};
Cursor c = nDB.query(N_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(ID_ROW);
int cName = c.getColumnIndex(ID_COURSENAME);
int cTopic = c.getColumnIndex(ID_TOPIC);
int cDescription = c.getColumnIndex(ID_DESCRIPTION);
int cLength = c.getColumnIndex(ID_LENGTH);
int cRating = c.getColumnIndex(ID_RATING);
//loop
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(cName) + " " + c.getString(cTopic) + " " + c.getString(cDescription) + " " + c.getString(cLength) + " " + c.getString(cRating) + "\n ";
}
return result;
}
public String getN(Long ls) {
// TODO Auto-generated method stub
String[] columns = new String[]{ID_ROW, ID_COURSENAME, ID_TOPIC, ID_DESCRIPTION, ID_LENGTH, ID_RATING};
Cursor c =nDB.query(N_TABLE, columns, ID_ROW + "=" + ls, null, null, null, null);
if(c != null){
c.moveToFirst();
String ns = c.getString(1);
return ns;
}
return null;
}
public String getT(Long ls) {
// TODO Auto-generated method stub
String[] columns = new String[]{ID_ROW, ID_COURSENAME, ID_TOPIC, ID_DESCRIPTION, ID_LENGTH, ID_RATING};
Cursor c =nDB.query(N_TABLE, columns, ID_ROW + "=" + ls, null, null, null, null);
if(c != null){
c.moveToFirst();
String ts = c.getString(2);
return ts;
}
return null;
}
public String getD(Long ls) {
// TODO Auto-generated method stub
String[] columns = new String[]{ID_ROW, ID_COURSENAME, ID_TOPIC, ID_DESCRIPTION, ID_LENGTH, ID_RATING};
Cursor c =nDB.query(N_TABLE, columns, ID_ROW + "=" + ls, null, null, null, null);
if(c != null){
c.moveToFirst();
String nd = c.getString(3);
return nd;
}
return null;
}
public String getL(Long ls) {
// TODO Auto-generated method stub
String[] columns = new String[]{ID_ROW, ID_COURSENAME, ID_TOPIC, ID_DESCRIPTION, ID_LENGTH, ID_RATING};
Cursor c =nDB.query(N_TABLE, columns, ID_ROW + "=" + ls, null, null, null, null);
if(c != null){
c.moveToFirst();
String nl = c.getString(4);
return nl;
}
return null;
}
public String getR(Long ls) {
// TODO Auto-generated method stub
String[] columns = new String[]{ID_ROW, ID_COURSENAME, ID_TOPIC, ID_DESCRIPTION, ID_LENGTH, ID_RATING};
Cursor c =nDB.query(N_TABLE, columns, ID_ROW + "=" + ls, null, null, null, null);
if(c != null){
c.moveToFirst();
String nr = c.getString(5);
return nr;
}
return null;
}
public void edit(long eRowl, String eCo, String eTo, String eDe,
String eLe, String eRa) throws SQLException {
// TODO Auto-generated method stub
ContentValues cvEdit = new ContentValues();
cvEdit.put(ID_COURSENAME, eCo);
cvEdit.put(ID_TOPIC, eTo);
cvEdit.put(ID_DESCRIPTION, eDe);
cvEdit.put(ID_LENGTH, eLe);
cvEdit.put(ID_RATING, eRa);
nDB.update(N_TABLE, cvEdit, ID_ROW + "=" + eRowl, null);
}}
really would appreciate your help
Thanks for your screenshot.Could you please improve your code to this:
}catch(Exception e) {
String error = e.getMessage(); //instead of String error = e.toString();
...
So we can see the actual cause.
Can you please make the "don't works" dialog large? I think some text is being trimmed.
I believe you are trying to parse an empty string "".
I'm working on Android 2.0 and am trying to receive a list of all contacts.
Since android.provider.Contacts.People is deprecated, I have to use android.provider.ContactsContract, But I can't find a proper example of how to use it (ex: retrieve a list of all contacts on the phonebook).
Anyone knows where to find such an example?
First, ensure that you have added
<uses-permission android:name="android.permission.READ_CONTACTS"/>
to your AndroidManifest.xml file, then you can loop through your phone contacts like this:
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts._ID));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Boolean.parseBoolean(hasPhone)) {
// You know it has a number so now query it like this
Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
while (emails.moveToNext()) {
// This would allow you get several email addresses
String emailAddress = emails.getString(
emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
}
cursor.close();
Additionally, you can loop through your contacts and simply get the name and phone number like this:
Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while(people.moveToNext()) {
int nameFieldColumnIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String contact = people.getString(nameFieldColumnIndex);
int numberFieldColumnIndex = people.getColumnIndex(PhoneLookup.NUMBER);
String number = people.getString(numberFieldColumnIndex);
}
people.close();
Furthermore, if you need to get things like notes from a contact then you will need to use a different URI, like the following (feel free to use this method):
private String getNote(long contactId) {
String note = null;
String[] columns = new String[] { ContactsContract.CommonDataKinds.Note.NOTE };
String where = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] whereParameters = new String[]{Long.toString(contactId), ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor contacts = getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, where, whereParameters, null);
if (contacts.moveToFirst()) {
rv = contacts.getString(0);
}
contacts.close();
return note;
}
Notice this time I used not only the contact id but the mime type for the query.
Great to see some useful info, it is frustrating how poorly this important topic is covered by docs and such. After too much hacking about I thought I would share a little code also. The following code is a little prettier and get the same thing done more efficiently.
Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
};
String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'";
Cursor contacts = managedQuery(contactUri, PROJECTION, SELECTION, null, null );
The above chunk of code returns a Cursor that points to the resulting query that only contains those rows that have a phone number. This is nice since you typically have many contacts without numbers. Furthermore, the PROJECTION limits the amount of data that is returned.
String key, value, phoneNumber;
Hashtable contactPhoneInfo = new Hashtable<String, String>();
Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String [] PHONES_PROJECTION = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };
String PHONE_SELECTION = null;
contacts.moveToFirst();
do{
long contactId = contacts.getLong(idColumnIndex);
PHONE_SELECTION = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId;
Cursor phones = managedQuery(phoneUri,
PHONES_PROJECTION,
null,
null,
ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY + " DESC");
phones.moveToFirst();
key = phones.getString(0).replaceAll("\\D", "");
value = contacts.getString(nameColumnIndex);
contactPhoneInfo.put(key, value);
}while(contacts.moveToNext());
contacts.close();
}
The above chunk gets the phone number associated with each contact id that has a phone number. I store all the info in a hash table and with a key value of the phone number. I stripped the phone number of all none digit info also. For some reason even though ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER is valid if you include that in the projection argument it breaks the query, I don't know why and it is frustrating that it does.
The second part of the code above is too slow, all the query calls just bog everything down. The following code is much faster. Just grab all the rows for the phone content and use the contact_ids to sort the data you want.
Cursor phones = managedQuery(phoneUri,
PHONES_PROJECTION,
PHONE_SELECTION,
null,
ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY + " DESC");
contacts.moveToFirst();
do{
value = "";
key = contacts.getString(idColumnIndex);
contactPhoneInfo.put(key, value);
}while(contacts.moveToNext());
phones.moveToFirst();
Set keySet = contactPhoneInfo.keySet();
idColumnIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
int numColumnIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
do{
key = phones.getString(idColumnIndex);
if(keySet.contains(key)){
value = phones.getString(numColumnIndex).replaceAll("\\D", "");
contactPhoneInfo.put(key, value);
}
}while(phones.moveToNext());
You end up with a hashtable with all the info you want in it. Of course you could put whatever info you want into the data structure. The second way of doing it is much much faster.
Just want to add, when you are retrieving the contacts you might get a lot of "garbage" contacts - for example some email addresses that a user has at some point send an email to, but are not aggregated... If you want only the contacts visible to the user, as in the Androids own contacts application you need to restrict the selection to only IN_VISIBLE_GROUP.
String where = ContactsContract.Contacts.IN_VISIBLE_GROUP + "= ? ";
String[] selectionArgs = new String[] { "1" };
I think it is important to have the code from this URL http://coderzheaven.com/2011/06/get-all-details-from-contacts-in-android/ on StackOverflow cause at times links like that go down.
public void readContacts(){
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
System.out.println("name : " + name + ", ID : " + id);
// get the phone number
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("phone" + phone);
}
pCur.close();
// get email and type
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
System.out.println("Email " + email + " Email Type : " + emailType);
}
emailCur.close();
// Get note.......
String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] noteWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
if (noteCur.moveToFirst()) {
String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
System.out.println("Note " + note);
}
noteCur.close();
//Get Postal Address....
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
// Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,
// null, null, null, null);
Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, addrWhere, addrWhereParams, null);
while(addrCur.moveToNext()) {
String poBox = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
String street = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String city = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String postalCode = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
String country = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
// Do something with these....
}
addrCur.close();
// Get Instant Messenger.........
String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] imWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE};
Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, imWhere, imWhereParams, null);
if (imCur.moveToFirst()) {
String imName = imCur.getString(
imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
String imType;
imType = imCur.getString(
imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
}
imCur.close();
// Get Organizations.........
String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (orgCur.moveToFirst()) {
String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
}
orgCur.close();
}
}
}
}
emphasized text
I found very easy solution to read contacts. (boring to write code for reading each value so it's good to use wrapper class for contacts)
Of course <uses-permission android:name="android.permission.READ_CONTACTS"/>
ContactList.java
package com.test;
import java.util.ArrayList;
public class ContactList {
private ArrayList<Contact> contacts = new ArrayList<Contact>();
public ArrayList<Contact> getContacts() {
return contacts;
}
public void setContacts(ArrayList<Contact> contacts) {
this.contacts = contacts;
}
public void addContact(Contact contact) {
this.contacts.add(contact);
}
public ContactList() {
}
}
Contact.java
package com.test;
import java.util.ArrayList;
public class Contact {
private String id;
private String displayName;
private ArrayList<Phone> phone;
private ArrayList<Email> email;
private ArrayList<String> notes;
private ArrayList<Address> addresses = new ArrayList<Address>();
private ArrayList<IM> imAddresses;
private Organization organization;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public ArrayList<Phone> getPhone() {
return phone;
}
public void setPhone(ArrayList<Phone> phone) {
this.phone = phone;
}
public void addPhone(Phone phone) {
this.phone.add(phone);
}
public ArrayList<Email> getEmail() {
return email;
}
public void setEmail(ArrayList<Email> email) {
this.email = email;
}
public void addEmail(Email email) {
this.email.add(email);
}
public ArrayList<String> getNotes() {
return notes;
}
public void setNotes(ArrayList<String> notes) {
this.notes = notes;
}
public void AddNotes(String notes){
this.notes.add(notes);
}
public ArrayList<Address> getAddresses() {
return addresses;
}
public void setAddresses(ArrayList<Address> addresses) {
this.addresses = addresses;
}
public void addAddress(Address address) {
this.addresses.add(address);
}
public ArrayList<IM> getImAddresses() {
return imAddresses;
}
public void setImAddresses(ArrayList<IM> imAddresses) {
this.imAddresses = imAddresses;
}
public void addImAddresses(IM imAddr) {
this.imAddresses.add(imAddr);
}
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
}
Address.java
package com.test;
public class Address {
private String poBox;
private String street;
private String city;
private String state;
private String postalCode;
private String country;
private String type;
private String asString = "";
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPoBox() {
return poBox;
}
public void setPoBox(String poBox) {
this.poBox = poBox;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String toString() {
if (this.asString.length() > 0) {
return(this.asString);
} else {
String addr = "";
if (this.getPoBox() != null) {
addr = addr + this.getPoBox() + "n";
}
if (this.getStreet() != null) {
addr = addr + this.getStreet() + "n";
}
if (this.getCity() != null) {
addr = addr + this.getCity() + ", ";
}
if (this.getState() != null) {
addr = addr + this.getState() + " ";
}
if (this.getPostalCode() != null) {
addr = addr + this.getPostalCode() + " ";
}
if (this.getCountry() != null) {
addr = addr + this.getCountry();
}
return(addr);
}
}
public Address(String asString, String type) {
this.asString = asString;
this.type = type;
}
public Address(String poBox, String street, String city, String state,
String postal, String country, String type) {
this.setPoBox(poBox);
this.setStreet(street);
this.setCity(city);
this.setState(state);
this.setPostalCode(postal);
this.setCountry(country);
this.setType(type);
}
}
Email.java
package com.test;
public class Email {
private String address;
private String type;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getType() {
return type;
}
public void setType(String t) {
this.type = t;
}
public Email(String a, String t) {
this.address = a;
this.type = t;
}
}
Im.java
package com.test;
public class IM {
private String name;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public IM(String name, String type) {
this.name = name;
this.type = type;
}
}
Organization.java
package com.test;
public class Organization {
private String organization = "";
private String title = "";
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Organization() {
}
public Organization(String org, String title) {
this.organization = org;
this.title = title;
}
}
Phone.java
package com.test;
public class Phone {
private String number;
private String type;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Phone(String n, String t) {
this.number = n;
this.type = t;
}
}
ContactAPI.java
package com.test;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
public abstract class ContactAPI {
private static ContactAPI api;
public static ContactAPI getAPI() {
if (api == null) {
String apiClass;
if (Integer.parseInt(Build.VERSION.SDK) >= Build.VERSION_CODES.ECLAIR) {
apiClass = "com.*********.ContactAPISdk5";
} else {
apiClass = "com.*********.ContactAPISdk3";
}
try {
Class<? extends ContactAPI> realClass = Class.forName(apiClass).
asSubclass(ContactAPI.class);
api = realClass.newInstance();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return api;
}
public abstract Intent getContactIntent();
public abstract ContactList newContactList();
public abstract Cursor getCur();
public abstract void setCur(Cursor cur);
public abstract ContentResolver getCr();
public abstract void setCr(ContentResolver cr);
}
ContactAPISdk5.java
package com.test;
import java.util.ArrayList;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.provider.ContactsContract;
public class ContactAPISdk5 extends ContactAPI {
private Cursor cur;
private ContentResolver cr;
public Cursor getCur() {
return cur;
}
public void setCur(Cursor cur) {
this.cur = cur;
}
public ContentResolver getCr() {
return cr;
}
public void setCr(ContentResolver cr) {
this.cr = cr;
}
public Intent getContactIntent() {
return(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI));
}
public ContactList newContactList() {
ContactList contacts = new ContactList();
String id;
this.cur = this.cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (this.cur.getCount() > 0) {
while (cur.moveToNext()) {
Contact c = new Contact();
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
c.setId(id);
c.setDisplayName(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
c.setPhone(this.getPhoneNumbers(id));
}
c.setEmail(this.getEmailAddresses(id));
c.setNotes(this.getContactNotes(id));
c.setAddresses(this.getContactAddresses(id));
c.setImAddresses(this.getIM(id));
c.setOrganization(this.getContactOrg(id));
contacts.addContact(c);
}
}
return(contacts);
}
public ArrayList<Phone> getPhoneNumbers(String id) {
ArrayList<Phone> phones = new ArrayList<Phone>();
Cursor pCur = this.cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
phones.add(new Phone(
pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
, pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))
));
}
pCur.close();
return(phones);
}
public ArrayList<Email> getEmailAddresses(String id) {
ArrayList<Email> emails = new ArrayList<Email>();
Cursor emailCur = this.cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
Email e = new Email(emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA))
,emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE))
);
emails.add(e);
}
emailCur.close();
return(emails);
}
public ArrayList<String> getContactNotes(String id) {
ArrayList<String> notes = new ArrayList<String>();
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] whereParameters = new String[]{id,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null);
if (noteCur.moveToFirst()) {
String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
if (note.length() > 0) {
notes.add(note);
}
}
noteCur.close();
return(notes);
}
public ArrayList<Address> getContactAddresses(String id) {
ArrayList<Address> addrList = new ArrayList<Address>();
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] whereParameters = new String[]{id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null);
while(addrCur.moveToNext()) {
String poBox = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
String street = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String city = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String postalCode = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
String country = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
Address a = new Address(poBox, street, city, state, postalCode, country, type);
addrList.add(a);
}
addrCur.close();
return(addrList);
}
public ArrayList<IM> getIM(String id) {
ArrayList<IM> imList = new ArrayList<IM>();
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] whereParameters = new String[]{id,
ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE};
Cursor imCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null);
if (imCur.moveToFirst()) {
String imName = imCur.getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
String imType;
imType = imCur.getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
if (imName.length() > 0) {
IM im = new IM(imName, imType);
imList.add(im);
}
}
imCur.close();
return(imList);
}
public Organization getContactOrg(String id) {
Organization org = new Organization();
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] whereParameters = new String[]{id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = this.cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParameters, null);
if (orgCur.moveToFirst()) {
String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
if (orgName.length() > 0) {
org.setOrganization(orgName);
org.setTitle(title);
}
}
orgCur.close();
return(org);
}
}
ContactAPISdk3.java
package com.test;
import java.util.ArrayList;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.provider.Contacts;
import android.provider.Contacts.People;
public class ContactAPISdk3 extends ContactAPI {
private Cursor cur;
private ContentResolver cr;
public Cursor getCur() {
return cur;
}
public void setCur(Cursor cur) {
this.cur = cur;
}
public ContentResolver getCr() {
return cr;
}
public void setCr(ContentResolver cr) {
this.cr = cr;
}
public Intent getContactIntent() {
return(new Intent(Intent.ACTION_PICK, People.CONTENT_URI));
}
public ContactList newContactList() {
ContactList contacts = new ContactList();
String id="";
this.cur = this.cr.query(People.CONTENT_URI,
null, null, null, null);
if (this.cur.getCount() > 0) {
while (cur.moveToNext()) {
Contact c = new Contact();
id = cur.getString(cur.getColumnIndex(People._ID));
c.setId(id);
c.setDisplayName(cur.getString(cur.getColumnIndex(People.DISPLAY_NAME)));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(People.PRIMARY_PHONE_ID))) > 0) {
c.setPhone(this.getPhoneNumbers(id));
}
c.setEmail(this.getEmailAddresses(id));
ArrayList<String> notes = new ArrayList<String>();
notes.add(cur.getString(cur.getColumnIndex(People.NOTES)));
c.setNotes(notes);
c.setAddresses(this.getContactAddresses(id));
c.setImAddresses(this.getIM(id));
c.setOrganization(this.getContactOrg(id));
contacts.addContact(c);
}
}
return(contacts);
}
public ArrayList<Phone> getPhoneNumbers(String id) {
ArrayList<Phone> phones = new ArrayList<Phone>();
Cursor pCur = this.cr.query(
Contacts.Phones.CONTENT_URI,
null,
Contacts.Phones.PERSON_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
phones.add(new Phone(
pCur.getString(pCur.getColumnIndex(Contacts.Phones.NUMBER))
, pCur.getString(pCur.getColumnIndex(Contacts.Phones.TYPE))
));
}
pCur.close();
return(phones);
}
public ArrayList<Email> getEmailAddresses(String id) {
ArrayList<Email> emails = new ArrayList<Email>();
Cursor emailCur = this.cr.query(
Contacts.ContactMethods.CONTENT_EMAIL_URI,
null,
Contacts.ContactMethods.PERSON_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
Email e = new Email(emailCur.getString(emailCur.getColumnIndex(Contacts.ContactMethods.DATA))
,emailCur.getString(emailCur.getColumnIndex(Contacts.ContactMethods.CONTENT_EMAIL_TYPE))
);
emails.add(e);
}
emailCur.close();
return(emails);
}
public ArrayList<Address> getContactAddresses(String id) {
ArrayList<Address> addrList = new ArrayList<Address>();
String where = Contacts.ContactMethods.PERSON_ID + " = ? AND " + Contacts.ContactMethods.KIND + " = ?";
String[] whereParameters = new String[]{id,
Contacts.ContactMethods.CONTENT_POSTAL_ITEM_TYPE};
Cursor addrCur = this.cr.query(Contacts.ContactMethods.CONTENT_URI, null, where, whereParameters, null);
while(addrCur.moveToNext()) {
String addr = addrCur.getString(addrCur.getColumnIndex(Contacts.ContactMethodsColumns.DATA));
String type = addrCur.getString(addrCur.getColumnIndex(Contacts.ContactMethodsColumns.TYPE));
Address a = new Address(addr, type);
addrList.add(a);
}
addrCur.close();
return(addrList);
}
public ArrayList<IM> getIM(String id) {
ArrayList<IM> imList = new ArrayList<IM>();
String where = Contacts.ContactMethods.PERSON_ID + " = ? AND " + Contacts.ContactMethods.KIND + " = ?";
String[] whereParameters = new String[]{id,
Contacts.ContactMethods.CONTENT_IM_ITEM_TYPE};
Cursor imCur = this.cr.query(Contacts.ContactMethods.CONTENT_URI, null, where, whereParameters, null);
if (imCur.moveToFirst()) {
String imName = imCur.getString(imCur.getColumnIndex(Contacts.ContactMethodsColumns.DATA));
String imType = imCur.getString(imCur.getColumnIndex(Contacts.ContactMethodsColumns.TYPE));
if (imName.length() > 0) {
IM im = new IM(imName, imType);
imList.add(im);
}
}
imCur.close();
return(imList);
}
public Organization getContactOrg(String id) {
Organization org = new Organization();
String where = Contacts.ContactMethods.PERSON_ID + " = ?";
String[] whereParameters = new String[]{id};
Cursor orgCur = this.cr.query(Contacts.Organizations.CONTENT_URI, null, where, whereParameters, null);
if (orgCur.moveToFirst()) {
String orgName = orgCur.getString(orgCur.getColumnIndex(Contacts.Organizations.COMPANY));
String title = orgCur.getString(orgCur.getColumnIndex(Contacts.Organizations.TITLE));
if (orgName.length() > 0) {
org.setOrganization(orgName);
org.setTitle(title);
}
}
orgCur.close();
return(org);
}
}
Note : Don't forget to change package name instead *******.
Source (link can be die any time :))
Put this ....
Cursor phones =
getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String Number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
Let me know if any issue.
This part wouldn't work for me:
while (phones.moveToNext()) {
String phoneNumber = phones.getString(
phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
}
If I use this, though, it does:
while (phones.moveToNext()) {
String pdata = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
Log.v("DATA",pdata);
}
You can use "ContactManager" example from android developer's site
(OR)
Go to the location where you have set the path to download android-sdk in your system. In android-sdk-mac_x86/samples/android-10 folder, you can see "ContactManager" example.
I have tried using this example, worked well in my application.
I'm using Samsung Galaxy Note 4, and I donno why none of the above worked for me.
I mixed up some and made this woking..
Cursor people = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
people.moveToFirst();
while(people.moveToNext()) {
int nameFieldColumnIndex = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String contact = people.getString(nameFieldColumnIndex);
int numberFieldColumnIndex = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);
String number = people.getString(numberFieldColumnIndex);
dbWriter.execSQL("Insert Into ContactsList (ContactName, ContactNumber) Values (" +
"'" + contact.replace("'", "''") + "', '" + number.replace("'", "''") + "')");
}
people.close();