Contact list isn't in Alphabetical order in Listview - android

I am using the Android Eclair 2.1 platform.
The working behind this code is, it will access all the contacts from the Emulator and will display in the list view for each contact like this
Contact Name, Contact Number, Email
There are 2 issues for this code is
I did run the program, after that I created a new contact it won't be in alphabetical order
[ eg : when I create a name starting from B it wouldn't go after A, instead it go to the last place ]
2.If a contact has no Email or Number it will receive the previous contact's Email or Number
Here is the code
public class GetAllDatas extends Activity {
ListView lvItem;
private Button btnAdd;
String displayName="", emailAddress="", phoneNumber="";
ArrayList<String> contactlist=new ArrayList<String>();
ArrayAdapter<String> itemAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvItem = (ListView)this.findViewById(R.id.lvitems);
btnAdd = (Button)this.findViewById(R.id.btnAddItem);
itemAdapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,contactlist);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
readContacts();
}
});
}
private void readContacts()
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
displayName =Cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME) );
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emails = cr.query(Email.CONTENT_URI,null,Email.CONTACT_ID + " = " + id, null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(Email.DATA));
break;
}
emails.close();
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PH ONE_NUMBER))) > 0)
{
Cursor pCur =cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDat aKinds.Phone.CONTACT_ID +" = ?",new String[]{id}, null);
while (pCur.moveToNext())
{
phoneNumber =pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
pCur.close();
}
// To display the Details
contactlist.add(displayName+", "+phoneNumber+", "+ emailAddress+"\n");
itemAdapter.notifyDataSetChanged();
}
cursor.close();
}
}
Any link or site to refer and study to solve this problems if so send me the link ?

Check the tested code below
package stack.examples;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class GetAllDatas extends Activity {
ListView lvItem;
private Button btnAdd;
String displayName="", emailAddress="", phoneNumber="";
ArrayList<String> contactlist=new ArrayList<String>();
ArrayAdapter<String> itemAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvItem = (ListView)this.findViewById(R.id.listView_items);
btnAdd = (Button)this.findViewById(R.id.btnAddItem);
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,contactlist);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
readContacts();
}
});
}
private void readContacts()
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emails = cr.query(Email.CONTENT_URI,null,Email.CONTACT_ID + " = " + id, null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(Email.DATA));
break;
}
emails.close();
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{id}, null);
while (pCur.moveToNext())
{
phoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
pCur.close();
}
contactlist.add(displayName+","+phoneNumber+","+ emailAddress);
}
cursor.close();
sortList(contactlist);
itemAdapter.notifyDataSetChanged();
}
private static void sortList(List<String> aItems){
Collections.sort(aItems, String.CASE_INSENSITIVE_ORDER);
}
}
To sort the ArrayList in Alphabetical order, you can use
Collections.sort(aItems, String.CASE_INSENSITIVE_ORDER);
Happy Coding !!!

When you query the database you are missing the orderBy:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
replace the last null with the column to sort by:
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

The last parameter of the query method expects the sorting order.
Please check the documentation query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder).
sortOrder How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.

Related

Displaying the phone number of a contact in Android Contact Content Provider

i am trying to write a program that would display the id, name and phone number of a contact in android. So far the Id and Names of the contact are displayed but the number of the contact doesn't. Can someone help me, below is the code for my program:
package com.example.oghenekaroedoh.provider;
import android.app.ListActivity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.CursorAdapter;
import android.widget.SimpleCursorAdapter;
public class Provider2Activity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provider);
Uri allContacts = ContactsContract.Contacts.CONTENT_URI;
//query string for our contacts
//Uri allContacts = Uri.parse("content://contacts/people");
//declare our cursor
Cursor c;
String[] projection = new String[]
{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER};
//---detect the android version
//---Projection, Filtering, and sorting
/* >>The second parameter of the managedQuery() method (third parameter for the CursorLoader class)
controls how many columns are returned by the query; this parameter is known as the projection
>>The third parameter of the managedQuery() method (fourth parameter for the CursorLoader class)
enable you to specify a SQL WHERE clause to filter the result of the query
>>The fourth parameter of the managedQuery() method (the fifth parameter for the CursorLoader class)
enables you to specify a SQL ORDER BY clause to sort the result of the query, either in ascending or descending order
* */
if (android.os.Build.VERSION.SDK_INT <11) {
//---if the device ids running on OS before Honeycomb
//use the managedQuery() of the Activity class to retrieve a managed cursor
c = managedQuery(allContacts, projection, null, null, null);
}
else {
//---Honeycomb and later use the cursor loader class to retrieve managed cursor---
CursorLoader cursorLoader = new CursorLoader(
this,
allContacts,
projection,
null,
null ,
null);
c = cursorLoader.loadInBackground();
}
//create columns for the contacts display name and the column
String[] columns = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts._ID};
int[] views = new int[] {R.id.contactName, R.id.contactID};
SimpleCursorAdapter adapter;
//detect the android version again..s
if (android.os.Build.VERSION.SDK_INT <11) {
//---if it is before Honeycomb---
//use the SimpleCursorAdapter class to map the cursor to a view (like textViews imageViews e.t.c)
adapter = new SimpleCursorAdapter(
this, R.layout.activity_provider, c, columns, views);
}
else {
//---Honeycomb and later---
////use the SimpleCursorAdapter class to map the cursor to a view (like textViews imageViews e.t.c)
//with an extra parameter known as CursorAdapter.FLAG_REGISTER_CURRENT_OBSERVER
adapter = new SimpleCursorAdapter(
this, R.layout.activity_provider, c, columns, views,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
}
this.setListAdapter(adapter);
PrintContacts(c);
}
private void PrintContacts(Cursor c)
{
//---display the contact id and name and phone number----
if (c.moveToFirst()) {
do{
//---get the contact id and name
String contactID = c.getString(c.getColumnIndex(
ContactsContract.Contacts._ID));
String contactDisplayName =
c.getString(c.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
Log.v("Content Providers", contactID + ", " +
contactDisplayName);
//---get phone number---
int hasPhone =
c.getInt(c.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone == 1) {
Cursor phoneCursor =
getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " +
contactID, null, null);
while (phoneCursor.moveToNext()) {
Log.v("Content Providers",
phoneCursor.getString(
phoneCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phoneCursor.close();
}
} while (c.moveToNext());
}
}
}
I got your example working by adding a CustomAdapter MyClassAdapter which extends ArrayAdapter, and populating an ArrayList of Contact objects.
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class Provider2Activity extends ListActivity {
ArrayList<Contact> contacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provider2);
contacts = new ArrayList<Contact>();
Uri allContacts = ContactsContract.Contacts.CONTENT_URI;
//declare our cursor
Cursor c;
String[] projection = new String[]
{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER};
/* >>The second parameter of the managedQuery() method (third parameter for the CursorLoader class)
controls how many columns are returned by the query; this parameter is known as the projection
>>The third parameter of the managedQuery() method (fourth parameter for the CursorLoader class)
enable you to specify a SQL WHERE clause to filter the result of the query
>>The fourth parameter of the managedQuery() method (the fifth parameter for the CursorLoader class)
enables you to specify a SQL ORDER BY clause to sort the result of the query, either in ascending or descending order
* */
if (android.os.Build.VERSION.SDK_INT <11) {
//---if the device ids running on OS before Honeycomb
//use the managedQuery() of the Activity class to retrieve a managed cursor
c = managedQuery(allContacts, projection, null, null, null);
}
else {
//---Honeycomb and later use the cursor loader class to retrieve managed cursor---
CursorLoader cursorLoader = new CursorLoader(
this,
allContacts,
projection,
null,
null ,
null);
c = cursorLoader.loadInBackground();
}
PrintContacts(c);
MyClassAdapter adapter;
//detect the android version again..
if (android.os.Build.VERSION.SDK_INT <11) {
//---if it is before Honeycomb---
adapter = new MyClassAdapter(
this, R.layout.row_line, contacts);
}
else {
//---Honeycomb and later---
adapter = new MyClassAdapter(
this, R.layout.row_line, contacts);
}
this.setListAdapter(adapter);
}
private void PrintContacts(Cursor c)
{
ContentResolver cr = getContentResolver();
//---display the contact id and name and phone number----
if (c.moveToFirst()) {
do{
//---get the contact id and name
String contactID = c.getString(c.getColumnIndex(
ContactsContract.Contacts._ID));
String contactDisplayName =
c.getString(c.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
Log.v("Content Providers", contactID + ", " +
contactDisplayName);
String contactDisplayPhone = "";
//---get phone number---
int hasPhone =
c.getInt(c.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone == 1) {
Cursor phoneCursor =
getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " +
contactID, null, null);
while (phoneCursor.moveToNext()) {
Log.v("Content Providers",
contactDisplayPhone = phoneCursor.getString(
phoneCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phoneCursor.close();
}
contacts.add(new Contact(contactDisplayName, contactID, contactDisplayPhone));
} while (c.moveToNext());
}
}
public class Contact{
public String contactName = "";
public String contactID = "";
public String contactNumber = "";
public Contact(String name, String id, String number){
contactName = name;
contactID = id;
contactNumber = number;
}
}
public class MyClassAdapter extends ArrayAdapter<Contact> {
private class ViewHolder {
private TextView name;
private TextView id;
private TextView number;
}
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<Contact> items) {
super(context, textViewResourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.row_line, parent, false);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.contactName);
viewHolder.id = (TextView) convertView.findViewById(R.id.contactID);
viewHolder.number = (TextView) convertView.findViewById(R.id.contactNumber);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Contact item = getItem(position);
if (item!= null) {
viewHolder.name.setText(item.contactName);
viewHolder.id.setText(item.contactID);
viewHolder.number.setText(item.contactNumber);
}
return convertView;
}
}
}
row_line.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="#+id/contactName"
android:textSize="16sp"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/contactID"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/contactNumber"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_provider2.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Provider2Activity">
<ListView
android:id="#android:id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</RelativeLayout>

I am unable to get the EMAIL_ID column in my code instead it gets the contact number in the emailid column

I am posting my code here.
Please help me to get the email address of the contact.
Also I am getting a random list; please help me to sort the data as well.
package com.example.webwerks.retrievingcontactsdemo;
import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import java.util.ArrayList;
public class MyActivity extends Activity {
private String name;
private String Number;
private String alternateNumber;
private String email_id;
RelativeLayout relativeLayout;
ListView listView;
ArrayList <String> arrayList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
listView = (ListView)findViewById(android.R.id.list);
getInformation(this.getContentResolver());
// relativeLayout = (RelativeLayout)findViewById(R.id.layoutRelative);
}
public void getInformation(ContentResolver contentResolver){
Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
while (phones.moveToNext()){
name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
email_id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
arrayList.add(name);
arrayList.add(Number);
arrayList.add(email_id);
}
phones.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my code. It gives me the contact name and contact number(primary) and email id column. Also, it shows me the contact number only.
And the data is not sorted according to my phone contact list.
Please help.
Thanks in advance :)
You need to execute another query using the id to get Email details of tat contact. SO check this code
Better to go with DataModel class:
public class ContactData
{
public String name;
public String email;
}
ArrayList<ContactData> data = new ArrayList<>();
public void getInformation(ContentResolver contentResolver){
Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
while (phones.moveToNext()){
String id = phones.getString(phones.getColumnIndex(ContactsContract.Contacts._ID));
Cursor cur1 = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cur1.moveToNext()) {
//to get the contact names
String name=cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Log.e("Name :", name);
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("Email", email);
if(email!=null){
Toast.makeText(this,
"Name : "+ name+" EMail : "+email, 1000)
.show();
}
}
dataList.add(contactData);
cur1.close();
}
phones.close();
}
cursor = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
contact = getContact(cursor, context.getContentResolver());
cursor.moveToNext();
}
private Contact getContact(Cursor cur , ContentResolver cr){
String contactID = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
if (contactID != null)
{
// for reading all contact
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{contactID}, null);
while (pCur.moveToNext()) {
String contactNumber = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contact_Number_Type = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
contact.setContact_Number(contactNumber);
contact.setContact_Number_Type(contact_Number_Type);
}
pCur.close();
// for reading all email id
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{contactID}, null);
while (emailCur.moveToNext()) {
String emailContact = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
contact.setContact_Email(emailContact);
contact.setContact_Email_Type(emailType);
}
emailCur.close();
}
}
Here Contact is a bean class

When I select contact name and address from contact list address data not retrieved

I need to get contact name and relevant address from contact list in android. I get the contact name and their phone number, but unfortunately unable to get the address details. When I select the contact address, it will return null every time.
I searched the google as well as stackoverflow. But unable to find a solution. When I searched I found that, address details are in another separate table, but I searched that table with id, but didn't return the data from the address table. So please help me to solve this problem. Thanks in advance,
Please find the code snippet which I used to get the contact details,
package com.contact.contacts;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.app.Activity;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity implements OnItemClickListener{
private ListView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
Cursor cur_phone = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
while (cur_phone.moveToNext()) {
String name = cur_phone
.getString(cur_phone
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = cur_phone
.getString(cur_phone
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String id = cur_phone.getString(cur_phone
.getColumnIndex(ContactsContract.Contacts._ID));
System.out.println("Cursor size : contact Name : "+name);
System.out.println("Cursor size : contact number : "+phoneNumber);
System.out.println("Cursor size : id : "+id);
Cursor cursor_address = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
cursor_address.close();
// get the data package containg the postal information for the contact
cursor_address = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
new String[]{ StructuredPostal.STREET,
StructuredPostal.CITY,
StructuredPostal.POSTCODE},
ContactsContract.Data.CONTACT_ID + "=? AND " +
StructuredPostal.MIMETYPE + "=?",
new String[]{String.valueOf(id), StructuredPostal.CONTENT_ITEM_TYPE},
null);
cursor_address.moveToFirst();
System.out.println("Cursor size : Outside while");
while (cursor_address.moveToNext()) {
System.out.println("Cursor size : Inside while");
// This while statement is not running
if(cursor_address != null && cursor_address.moveToFirst())
{
if (cursor_address.getCount() > 0) {
String Street = cursor_address.getString(cursor_address.getColumnIndex(StructuredPostal.STREET));
System.out.println("Address : "+Street);
String Postcode = cursor_address.getString(cursor_address.getColumnIndex(StructuredPostal.POSTCODE));
String City = cursor_address.getString(cursor_address.getColumnIndex(StructuredPostal.CITY));
}
else
{
System.out.println("Cursor is : " + cursor_address);
Log.i("Contact : ", "Cursor :" + cursor_address);
}
}
else
{
System.out.println("Cursor Null : " + cursor_address);
Log.i("Contact App : ", "Cursor null" + cursor_address);
}
}
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
public ArrayList<String> getName(){
ArrayList<String> mdetail=new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT "+COLUMN_PERSON_NAME+" from "+TABLE_DETAIL;
Cursor mCursor = db.rawQuery(selectQuery, null);
if(mCursor.moveToFirst()){
do {
mdetail.add(mCursor.getString(mCursor.getColumnIndex(COLUMN_PERSON_NAME)));
} while (mCursor.moveToNext());
}
mCursor.close();
db.close();
return mdetail;
}
if Your data is Sucessfully added in your database just use this code to retreive from database and show in list view like this....
if (!db.exists()) {
} else {
mListName=baseManager.getName();
listview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,mListName));
}
Finally I solve the problem, Please find the below answer,
package com.contact.contacts;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener {
private ListView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
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));
String phone = null;
String poBox = null;
String street = null;
String city = null;
String state = null;
String postalCode = null;
String country = null;
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Query for phone
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
// Get the phone number
phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
pCur.close();
}
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, addrWhere, addrWhereParams, null);
while(addrCur.moveToNext()) {
poBox = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
street = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
city = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
state = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
postalCode = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
country = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
}
addrCur.close();
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phone);
objContact.setAddressLine1(poBox);
objContact.setAddressLine2(street);
objContact.setCity(city);
objContact.setPostalCode(postalCode);
objContact.setCountry(country);
list.add(objContact);
ContactAdapter objAdapter = new ContactAdapter(ContactActivity.this,
R.layout.single_contact, list);
listView.setAdapter(objAdapter);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
} else {
showToast("No Contact Found!!!");
}
}
}
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> listview, View v, int position,
long id) {
// Event for item click
}
}

how to fetch contact number in android?

I am trying to fetch contact numbers in my application but it is showing only id and display name. Can anyone correct it? I don't know how to fetch the contact numbers. I am only trying to fetch the contact numbers not to add the contact numbers.
package com.data;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public final class ContactManager extends Activity
{
public static final String TAG = "ContactManager";
private Button mAddAccountButton;
private ListView mContactList;
private boolean mShowInvisible;
private CheckBox mShowInvisibleControl;
/**
* Called when the activity is first created. Responsible for initializing the UI.
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
Log.v(TAG, "Activity State: onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_manager);
// Obtain handles to UI objects
// mAddAccountButton = (Button) findViewById(R.id.addContactButton);
mContactList = (ListView) findViewById(R.id.contactList);
mShowInvisibleControl = (CheckBox) findViewById(R.id.showInvisible);
// Initialize class properties
mShowInvisible = false;
mShowInvisibleControl.setChecked(mShowInvisible);
// Register handler for UI elements
mShowInvisibleControl.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d(TAG, "mShowInvisibleControl changed: " + isChecked);
mShowInvisible = isChecked;
populateContactList();
}
});
// Populate the contact list
populateContactList();
}
private void populateContactList() {
Cursor cursor = getContacts();
String[] pno=new String[cursor.getCount()];
if(cursor.getCount()>0)
{
int i=0;
if(cursor.moveToFirst())
{
do
{
pno[i++]=(String)cursor.getString(0).toString() +" "+ (String)cursor.getString(1);
}while(cursor.moveToNext());
}
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(ContactManager.this,android.R.layout.simple_list_item_1,pno);
mContactList.setAdapter(adapter);
}
private Cursor getContacts()
{
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
};
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" +
(mShowInvisible ? "0" : "1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}
}
Modify your query projection to include also the ContactsContract.Contacts.HAS_PHONE_NUMBER column.
Then, inside the do-while loop, you can do:
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(hasPhone) > 0) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
String phoneNumber;
while (cursor.moveToNext()) { //iterate over all contact phone numbers
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
You need to use another content provider uri. I will point you to one answer of mine, so that I don't repeat myself in stackoverflow: https://stackoverflow.com/a/8646827/1108032. In this answer I fetch the name out of the phone number, but I really believe you can revert it easily.
You should use the Phone Uri or the new PhoneLookUp Uri to get display name and all phone numbers with contact id.
http://developer.android.com/reference/android/provider/ContactsContract.PhoneLookup.html

getting all phone book contact details into an array in android

I am getting all the phonebook contact details as an array. For that I wrote the following code:
package com.android.toggle2;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Toggle3 extends ListActivity
{
ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
// Now create a new list adapter bound to the cursor.
// SimpleListAdapter is designed for binding to a Cursor.
ListAdapter adapter = new SimpleCursorAdapter(this, // Context.
android.R.layout.simple_list_item_multiple_choice, // Specify the row template
// to use (here, two
// columns bound to the
// two retrieved cursor
// rows).
mCursor, // Pass in the cursor to bind to.
// Array of cursor columns to bind to.
new String[] { ContactsContract.Contacts.DISPLAY_NAME ,
ContactsContract.Contacts._ID},
// Parallel array of which template objects to bind to those
// columns.
new int[] { android.R.id.text1, android.R.id.text2 });
// Bind to our new adapter.
setListAdapter(adapter);
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private Cursor getContacts()
{
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,sortOrder);
}
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
//here i want to handle the event.and should display the details of that contacts in another screen .
//Toast.makeText(Toggle3.this,"Item in position " + position + " clicked",Toast.LENGTH_LONG).show();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
String ids = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
list.add(new BasicNameValuePair("name",name.toString()));
//String number = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.NUMBER));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
//Query phone here.
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{ids}, null);
while(pCur.moveToNext())
{
String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
list.add(new BasicNameValuePair("num",number.toString()));
}
pCur.close();
}//if
}//while
Log.i("array items", "" +list);
}//if
}//on click
}//class
While executing this application it's showing all my phonebook contacts in the application with checkboxes in each row. If I click on any name (list item) it stores all the contact details into an array. But I want to store only selected contacts. What should I change in my code.. please do needful help
I have modified your code. Now its working as per expectation. Vote my answer if it is helpful for you so that It will increase your ratings also
use the following code to retrieve contact from mobile.
I have tested. its working fine
public static void getContactNumbers(Context context) {
String contactNumber = null;
int contactNumberType = Phone.TYPE_MOBILE;
String nameOfContact = null;
if (ApplicationConstants.phoneContacts.size() <= 0) {
ContentResolver cr = context.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(BaseColumns._ID));
nameOfContact = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phones = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
while (phones.moveToNext()) {
contactNumber = phones.getString(phones
.getColumnIndex(Phone.NUMBER));
contactNumberType = phones.getInt(phones
.getColumnIndex(Phone.TYPE));
Log.i(TAG, "...Contact Name ...." + nameOfContact
+ "...contact Number..." + contactNumber);
}
phones.close();
}
}
}// end of contact name cursor
cur.close();
}
}
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));
}
public void readContacts()
{
int i=0;
Cursor cursor=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,null,null,null);
count=cursor.getCount();
names=new String[count];
phno=new String[count];
while(cursor.moveToNext())
{
names[i]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)) ;
phno[i]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
i++;
}

Categories

Resources