I need to get contact's photo. So I get the contact's id and ues the folowing function to get photo.
Log.i(MenuActivity.TAG, "START: getContactPhoto; PARAMETERS: id: " + String.valueOf(id));
Uri photoUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
Bitmap photo;
ContentResolver cr = context.getContentResolver();
InputStream is = ContactsContract.Contacts.openContactPhotoInputStream(cr, photoUri);
photo = BitmapFactory.decodeStream(is);
return photo;
And this to set the photo to imageView
if (photo != null) {
Log.d(MenuActivity.TAG, "Photo exists");
imageView.setImageBitmap(photo);
} else {
Log.e(MenuActivity.TAG, "No photo for contact " + name);
imageView.setImageResource(R.drawable.defult_foto);
}
My logcat:
START: getContactPhoto; PARAMETERS: id: 148
Photo uri: content://com.android.contacts/contacts/148
No photo for contact Ivan
The way I get contact id:
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Event.CONTACT_ID,
ContactsContract.CommonDataKinds.Event.START_DATE,
};
String where =
ContactsContract.Data.MIMETYPE + "= ? AND " +
ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
String[] selectionArgs = new String[]{ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE};
String sortOrder = null;
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(uri, projection, where, selectionArgs, sortOrder);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
try {
id = "no-id";
birthday = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// some code
} catch (Exception e) {
Log.e("Days", "No birthday date!");
}
}
}
cursor.close();
But it sais that none of my contact has photo, but it has. I belive smth is wrong. Any ideas?
P.S I'm a bit noob in andrid yet so if it won't be very difficult be specific
Use this sample code to fetch the thumbnails
Layout
<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"
tools:context=".MainActivity" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/spinner1"
android:layout_marginLeft="58dp"
android:layout_marginTop="60dp"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
Activity code
package com.example.contactsdisplaypic;
import java.io.ByteArrayInputStream;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.support.v4.widget.CursorAdapter;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
Context mContext;
public SimpleCursorAdapter sca;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
new LoadContactsTask().execute();
}
class LoadContactsTask extends AsyncTask<Void, Void, Cursor> {
#Override
protected Cursor doInBackground(Void... params) {
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Event.CONTACT_ID,
ContactsContract.CommonDataKinds.Event.START_DATE,
};
String where =
ContactsContract.Data.MIMETYPE + "= ? AND " +
ContactsContract.CommonDataKinds.Event.TYPE + "=" +
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
String[] selectionArgs = new String[]{ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE};
String sortOrder = null;
ContentResolver cr = mContext.getContentResolver();
Cursor cursor = cr.query(uri, projection, where, selectionArgs, sortOrder);
cursor.moveToFirst();
return cursor;
}
#Override
protected void onPostExecute(Cursor result) {
// create an array to specify which fields we want to display
String[] from = new String[]{ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Event.CONTACT_ID};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1, android.R.id.text2};
// create simple cursor adapter
sca =
new SimpleCursorAdapter(mContext, android.R.layout.simple_expandable_list_item_2, result, from, to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
sca.setDropDownViewResource( android.R.layout.simple_expandable_list_item_2 );
// get reference to our spinner
Spinner s = (Spinner) findViewById( R.id.spinner1 );
s.setAdapter(sca);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
Toast.makeText(mContext, "contact id " + sca.getCursor().getString(2), Toast.LENGTH_LONG).show();
new LoadPicturesTask().execute(sca.getCursor().getString(2));
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
}
}
private class LoadPicturesTask extends AsyncTask<String, Void, Bitmap[]> {
#Override
protected Bitmap[] doInBackground(String... contactId) {
Bitmap[] array = new Bitmap[2];
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
Long.parseLong(contactId[0]));
// thumbnail
Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri,
new String[] {Contacts.Photo.PHOTO}, null, null, null);
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
array[0] = BitmapFactory.decodeStream(new ByteArrayInputStream(data));
}
}
} finally {
cursor.close();
}
return array;
}
#Override
protected void onPostExecute(Bitmap[] result) {
if (result != null) {
ImageView img1 = (ImageView) findViewById(R.id.imageView1);
img1.setImageBitmap(result[0]);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I was able to fetch some contacts for whom birthday was stored and then the thumbnail was fetched for whom it was available.
Related
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 want to do the following.
Pick up three to five contacts out of a special group of contacts or all contacts.
In the list it would be nice to show the contact image.
The selected contacts should have the following information (contact-id, first name, the small version of the contact image to save it as a blob in the database)
I found solutions for the different aspects.
-select multiple contacts:
How to obtain the checked rows in a custom view list
-show contacts from one group
getting contacts from a specified group in android
- photo problem
Getting a Photo from a Contact
But I dont know how to put those together. It would be great if someone could help me putting it together.
Thank you very much!
Frank J.
Solved it, but cant post the answer for some hours.
Solution (not prettyfied yet)
package com.pinkpony.frankj.contactpicker2;
import android.app.Activity;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by Frank on 28.07.2014.
*/
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
List<String> name1 = new ArrayList<String>();
List<String> name2 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
List<String> img1 = new ArrayList<String>();
MyAdapter ma ;
Button select;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadGroups();
//Toast.makeText(MainActivity.this, toString(), Toast.LENGTH_LONG).show();
Log.d("LongValue", toString());
getAllCallLogs(this.getContentResolver());
ListView lv= (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............."+ma.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("..Not Checked......"+name1.get(i).toString());
}
}
//Toast.makeText(getApplicationContext(), checkedcontacts, 1000).show();
Toast.makeText(MainActivity.this, checkedcontacts, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
/* 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";
Cursor phones = cr.query(uri, projection, selection, selectionArgs,
sortOrder);
*/
// long groupId = id;
String[] cProjection = { ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID };
Cursor groupCursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
cProjection,
ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "= ?" + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'",
new String[] { String.valueOf(6) }, null);
if (groupCursor != null && groupCursor.moveToFirst())
{
do
{
int nameCoumnIndex = groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String name = groupCursor.getString(nameCoumnIndex);
String szFullname=name;
//long contactId = groupCursor.getLong(groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
long contactId = groupCursor.getLong(groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
// Log.d("your tag", "contact " + name + ":"+String.valueOf(contactId));
name1.add(name);
phno1.add(String.valueOf(contactId));
boolean foundToken = false;
// IDENTIFY Contact based on name and token
String szLookupKey = "";
Uri lkup = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, szFullname);
ContentResolver cr2 = getContentResolver();
Cursor idCursor = getContentResolver().query(lkup, null, null, null, null);
// get all the names
while (idCursor.moveToNext()) {
// get current row/contact ID = ID's are unreliable, so we will go for the lookup key
String szId = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts._ID));
String szName = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
szLookupKey = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
// for this contact ID, search the custom field
Log.d("", "Searching token:" + szId + " Name:" + szName + " LookupKey:" + szLookupKey);
//Log.d(LOG_TAG, "search: "+lid + " key: "+key + " name: "+name);
}
String whereName = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID + " = ?";
String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, String.valueOf(contactId) };
Cursor nameCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur.moveToNext()) {
String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String display = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
Log.d("your tag", "Vorname " + ":" + given);
name2.add(given);
}
nameCur.close();
} while (groupCursor.moveToNext());
groupCursor.close();
}
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
ImageView im1;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private void retrieveContactPhoto(Long contactID) {
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageBitmap(photo);
}
assert inputStream != null;
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public Bitmap openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri,
new String[] {ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return BitmapFactory.decodeStream(new ByteArrayInputStream(data));
}
}
} finally {
cursor.close();
}
return null;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
TextView tv= (TextView) vi.findViewById(R.id.textView1);
// tv1= (TextView) vi.findViewById(R.id.textView2);
im1= (ImageView) vi.findViewById(R.id.imageView1);
Bitmap photo = null;
Long contactID=Long.valueOf(phno1.get(position));
im1.setImageBitmap(openPhoto(contactID));
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText(""+ name1.get(position));
// tv1.setText(""+phno1.get(position));//
// retrieveContactPhoto(Long.valueOf(phno1.get(position)));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
private class GroupInfo {
String id;
String title;
#Override
public String toString() {
return title+ " ("+id+")";
}
public String getId() {
return id;
}
}
List<GroupInfo> groups = new ArrayList<GroupInfo>();
public void loadGroups() {
final String[] GROUP_PROJECTION = new String[] {
ContactsContract.Groups._ID,
ContactsContract.Groups.TITLE,
ContactsContract.Groups.SUMMARY_WITH_PHONES
};
Cursor c = getContentResolver().query(
ContactsContract.Groups.CONTENT_SUMMARY_URI,
GROUP_PROJECTION,
ContactsContract.Groups.DELETED+"!='1' AND "+
ContactsContract.Groups.GROUP_VISIBLE+"!='0' "
,
null,
null);
final int IDX_ID = c.getColumnIndex(ContactsContract.Groups._ID);
final int IDX_TITLE = c.getColumnIndex(ContactsContract.Groups.TITLE);
Map<String,GroupInfo> m = new HashMap<String, GroupInfo>();
while (c.moveToNext()) {
GroupInfo g = new GroupInfo();
g.id = c.getString(IDX_ID);
g.title = c.getString(IDX_TITLE);
int users = c.getInt(c.getColumnIndex(ContactsContract.Groups.SUMMARY_WITH_PHONES));
if (users>0) {
// group with duplicate name?
GroupInfo g2 = m.get(g.title);
if (g2==null) {
m.put(g.title, g);
groups.add(g);
} else {
g2.id+=","+g.id;
}
}
Log.d("LongValue", g.id+g.title);
}
c.close();
}
}
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
}
}
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
I want to fetch the photo of the contact while a user enters number.By using phone number i am getting users name but for image it shows null.
my code is following :
public class NewtempActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView img = (ImageView) findViewById(R.id.imageView1);
final EditText edit = (EditText) findViewById(R.id.editText1);
TextView txt = (TextView) findViewById(R.id.textView1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Girish", "Clicked");
String name = getContactNameFromNumber(edit.getText()
.toString(), getApplicationContext());
img.setImageBitmap(BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID));
Log.d("Girish",
""
+ (BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID)));
Toast.makeText(getApplicationContext(), name, name.length())
.show();
}
});
}
public String getContactNameFromNumber(String number, Context ctx) {
/*
* // define the columns I want the query to return String[] projection
* = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME,
* ContactsContract.PhoneLookup.NUMBER, };
*/
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
// Cursor c = ctx.getContentResolver().query( contactUri, projection,
// null,
Cursor c = ctx.getContentResolver().query(contactUri, null, null, null,
null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
return name;
}
// return the original number if no match was found
return number;
}
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(cr, uri);
// InputStream input = ContactsContract.Contacts.Photo
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
contactId);
Uri photoUri = Uri.withAppendedPath(contactUri,
Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri, null, null, null,
null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
}
please suggest me where i am doing wrong.I have added read contact permission also
by going through your code i came to know like You are trying to get the contact name from the number. and using that you want the contact image.. but you never called the functions which you made for the contact pic..:).. so what you can do is take id from the contact number and take photo on that id. so you will get the photo for the number..
package com.android.SampleProject;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class NewtempActivity extends Activity {
private long id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView img = (ImageView) findViewById(R.id.imageView1);
final EditText edit = (EditText) findViewById(R.id.editText1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("Girish", "Clicked");
String name = getContactNameFromNumber(edit.getText()
.toString(), getApplicationContext());
img.setImageBitmap(BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID));
img.setImageBitmap(loadContactPhoto(getContentResolver(), id));
Log.d("Girish",
""
+ (BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID)));
Toast.makeText(getApplicationContext(), name, name.length())
.show();
}
});
}
public String getContactNameFromNumber(String number, Context ctx) {
/*
* // define the columns I want the query to return String[] projection
* = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME,
* ContactsContract.PhoneLookup.NUMBER, };
*/
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
// Cursor c = ctx.getContentResolver().query( contactUri, projection,
// null,
Cursor c = ctx.getContentResolver().query(contactUri, null, null, null,
null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
id = c.getLong(c
.getColumnIndex(ContactsContract.PhoneLookup._ID));
return name;
}
// return the original number if no match was found
return number;
}
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(cr, uri);
// InputStream input = ContactsContract.Contacts.Photo
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
contactId);
Uri photoUri = Uri.withAppendedPath(contactUri,
Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri, null, null, null,
null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
}