problem with reading contacts in android - java

i'm trying to read contacts with this code but it only gets Contacts but not contacts data.Please
tell me am i going on a wrong path or what is wrong with this.
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while(contacts.moveToNext()) {
int contactIdColumnIndex = contacts.getColumnIndex(ContactsContract.Contacts._ID);
long contactId = contacts.getLong(contactIdColumnIndex);
System.out.println(contactId);
Cursor c = getContentResolver().query(Data.CONTENT_URI,
new String[] {Data._ID, Phone.NUMBER, Phone.TYPE},
Data.CONTACT_ID + "=?" + " AND "
+ Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'",
new String[] {String.valueOf(contactId)}, null);
//retrieving data
while(c.moveToNext()){
long Id=c.getLong(0);
String number=c.getString(1);
String type=c.getString(2);
String name=c.getString(3);
System.out.println(Id);
System.out.println(number);
System.out.println(type);
System.out.println(name);
}
c.close();
}
contacts.close();
This runs well when i debug this and it only print ContactIds only
1
2
3
4
but no data...(apologize for long question)

try this code
String number = "";
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) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
for(int i=0;i<pCur.getColumnCount();i++)
number = pCur.getString(i);
}
pCur.close();
pCur = null;
}
}
}
cur.close();
cur = null;
cr = null;

Related

How get only mobile numbers in contact

I have the below code to get contact name and number. How to get only mobile numbers and name in contact? A name in contact may have a few numbers. How to get mobile numbers for a name?
ContentResolver cr = activity.getContentResolver();
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
Try to use this code. Work for me.
private static final String[] PROJECTION =
{
Contacts._ID,
Contacts.LOOKUP_KEY,
Contacts.HAS_PHONE_NUMBER,
Build.VERSION.SDK_INT
>= Build.VERSION_CODES.HONEYCOMB ?
Contacts.DISPLAY_NAME_PRIMARY :
Contacts.DISPLAY_NAME
};
private static final String[] PROJECTION_PHONE =
{
Phone.NUMBER
};
private static final String SELECTION_PHONE = Phone.LOOKUP_KEY + " = ?";
HashMap<String, ArrayList<String>> contacts = new HashMap<>();
ContentResolver cr = context.getContentResolver();
Cursor cur = cr.query(Contacts.CONTENT_URI,
PROJECTION, null, null, null); //get contacts
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(Build.VERSION.SDK_INT
>= Build.VERSION_CODES.HONEYCOMB ?
Contacts.DISPLAY_NAME_PRIMARY :
Contacts.DISPLAY_NAME));
String lookUpKey = cur.getString(cur.getColumnIndex(Contacts.LOOKUP_KEY));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(Contacts.HAS_PHONE_NUMBER))) > 0) { //check if has numbers
Cursor pCur = cr.query(Phone.CONTENT_URI, PROJECTION_PHONE, SELECTION_PHONE,
new String[]{lookUpKey}, null); //get contacts phone numbers
ArrayList<String> phones = new ArrayList<>();
while (pCur.moveToNext()) {
String phone = pCur.getString(0);
phones.add(phone);
}
contacts.put(name, phones);
pCur.close();
}
}
}
cur.close();
You could query the ContactsContract.CommonDataKinds.Phone.TYPE column to determine the type of the number:
int type = phones.getInt(phones.
getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
if(type == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) {
phoneNumber = phones.getString(phones.
getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
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));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
// Query phone here. Covered next
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("Number", phoneNumber);
}
phones.close();
}
}
}
You will have to ask for this permission:
uses-permission android:name="android.permission.READ_CONTACTS"

How to search a column in sqlite by a string

I would like to return a true / false value when the string match with the column of sqlite. How can I implement the search function?
How to use cursor to do searching?
public boolean searchLuggage(String code) {
ArrayList<String> luggageCheck = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
try {
Cursor cursor = db.query(true, TABLE_LUGGAGES, new String[] { your field list }, SearchColumnname + "='" + code + "'", null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
luggageCheck.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LUGGAGE_TABLE = "CREATE TABLE " + TABLE_LUGGAGES + "(" + KEY_NAME + " TEXT NOT NULL," + KEY_CODE + " TEXT NOT NULL," + KEY_NUMBER + " TEXT NOT NULL );";
db.execSQL(CREATE_LUGGAGE_TABLE);
}
Replace this
Cursor cursor = db.query(true, TABLE_LUGGAGES, new String[] { your field list }, SearchColumnname + "='" + code + "'", null, null, null, null, null);
with this
Cursor cursor = db.query(true, TABLE_LUGGAGES, null, SearchColumnname + "= ?", new String[] { code }, null, null, null, null);

Change contact picture programmatically

I have a picture, that is stored into the android phone. I want to be able to change the picture of a contact.
What I've done so far is launch the contact picker, have the user select a contact, and then I get the URI of the selected contact. From this contact, I can get the associated rawContact and I use this code.
Uri rawContactPhotoUri = Uri.withAppendedPath(
ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId),
RawContacts.DisplayPhoto.CONTENT_DIRECTORY);
try {
AssetFileDescriptor fd =
getContentResolver().openAssetFileDescriptor(rawContactPhotoUri, "rw");
OutputStream os = fd.createOutputStream();
os.write(photo);
os.close();
fd.close();
} catch (IOException e) {
// Handle error cases.
}
The problem is, the AssetFIleDescriptor is always empty (when I call length on it, we always get -1).
I'm not asking for the entire solution, just some leads to follow that can help me to get that working. I cannot seem to find this problem already on StackOverflow, so any help would be appreciated.
EDIT
It's always when we ask for question that we find the solution.
I want to share it for other
So I gave up on android link and find another one :
http://wptrafficanalyzer.in/blog/programatically-adding-contacts-with-photo-using-contacts-provider-in-android-example/
The picture picker return the Uri of the selected contact, so with this you can get the Contact._ID of it :
// This is onActivityResult
final Uri uri = data.getData();
final Cursor cursor1 = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
final long contactId = cursor1.getLong(cursor1.getColumnIndex(Contacts._ID);
cursor1.close();
Then I had to get the RawContactId :
final Cursor cursor2 = getContentResolver().query(RawContacts.CONTENT_URI, null, RawContacts.Contact_ID + "=?", new String[] {String.valueOf(contactId)}, null);
cursor2.moveToFirst();
final long rawContactId = cursor2.getLong(cursor2.getColumnIndex(RawContacts._ID));
cursor2.close();
Then I had to get the Data._ID of the RawContacts (same way as above).
Then I used the ContentProviderOperations :
final ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(Data._ID, dataId),
.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, byteArrayOfThePicture);
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
And this is working like charm. Hope it helps
String contactId = "10001"; // change it as your IDs
if (mBitmap != null) {
// Picture
try {
ByteArrayOutputStream image = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, image);
Uri rawContactUri = null;
Cursor rawContactCursor = managedQuery(
ContactsContract.RawContacts.CONTENT_URI,
new String[] {
ContactsContract.RawContacts._ID
},
ContactsContract.RawContacts.CONTACT_ID + " = " + contactId,
null,
null);
if (!rawContactCursor.isAfterLast()) {
rawContactCursor.moveToFirst();
rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendPath("" + rawContactCursor.getLong(0)).build();
}
rawContactCursor.close();
ContentValues values = new ContentValues();
int photoRow = -1;
String where111 = ContactsContract.Data.RAW_CONTACT_ID + " == " +
ContentUris.parseId(rawContactUri) + " AND " + ContactsContract.Data.MIMETYPE + "=='" +
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = managedQuery(
ContactsContract.Data.CONTENT_URI,
null,
where111,
null,
null);
int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);
if (cursor.moveToFirst()) {
photoRow = cursor.getInt(idIdx);
}
cursor.close();
values.put(ContactsContract.Data.RAW_CONTACT_ID,
ContentUris.parseId(rawContactUri));
values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, image.toByteArray());
values.put(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
if (photoRow >= 0) {
getContentResolver().update(
ContactsContract.Data.CONTENT_URI,
values,
ContactsContract.Data._ID + " = " + photoRow, null);
} else {
getContentResolver().insert(
ContactsContract.Data.CONTENT_URI,
values);
}
} catch (Exception e) {
Log.e("!_##Image_Exception", e + "");
}
}
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
Log.e("#####UPLOADERR", e + "");
}

Display one Contact name with multiple numbers

I am trying to retrieve contacts from my phone that has only numbers and put them into an arrayList, view them in lazy adapter and on click of name I would like show only numbers. I managed to get the list of contacts and numbers but the problem is when I have a contact with multiple numbers it just adds up into the list.
Something like for e.g
David +1 508 656 9043
David +1 403 604 7053
David +1 212 608 7053
Instead I would like to show only David in the list and when I click it should show all the three numbers.
I tried this:
void getContactNumbers()
{
ContentResolver cr = getContentResolver();
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME+ " COLLATE LOCALIZED ASC";
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, sortOrder);
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));
Log.e("contact", "...Contact Name ...." + name);
if (Integer.parseInt(cur.getString(cur.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())
{
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.e("contact", "...Contact Name ...." + name + "...contact Number..." + phoneNo);
}
pCur.close();
}
}
}
}
How to solve this part?
Thanks!
Thanks Harshid. There was selection change instead of IN_VISIBLE_GROUP + " = '1'"; -
I added HAS_PHONE_NUMBER + " = '1'";
All contacts came up.. Hope the below code helps others!!
Thanks!
final Uri uri = ContactsContract.Contacts.CONTENT_URI;
final String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_ID
};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1'";
final String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cur = getContentResolver().query(uri, projection, selection, null, sortOrder);
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
String Sid = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.e("contact", "...Contact Name ...." + name);
// get the phone number
Cursor pCur = getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (pCur.moveToNext()) {
number = pCur.getString(pCur .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
pCur.close();
}
}
cur.close();
You have to this way query and get contact with multiple number.
final Uri uri = ContactsContract.Contacts.CONTENT_URI;
final String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_URI
};
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";
String[] selectionArgs = null;
final String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cur = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
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));
Log.e("contact", "...Contact Name ...." + name);
// get the phone number
Cursor pCur = getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (pCur.moveToNext()) {
number = pCur.getString(pCur .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
pCur.close();
}
}
cur.close();
Try this code if getting error then put comment otherwise enjoy..

Retrieve HOME Contact Number from address book

currently i have a application which will retrieve all the contact
details and will display all the available Contact Names.But now i want to retrieve Home,work numbers.I search for this everywhere but i couldn't. how can
i achieve this? please help me.
Thanks.
I used this code to get Home Numbers.
Cursor c = getContentResolver().query(Data.CONTENT_URI,
new String[] {Data._ID, Phone.NUMBER, Data.MIMETYPE},
Data.RAW_CONTACT_ID + "=?" + " AND "
+ Data.MIMETYPE + "='" + Phone.TYPE_HOME + "'",
new String[] {String.valueOf(contactId)}, null);
But what i need is to get Home,Work,Mobile (with name,email address,etc) numbers using single query.
using this code it always returns me type=0
Cursor c = getContentResolver().query(Data.CONTENT_URI,
null,
Data.CONTACT_ID + "=?",
new String[] {String.valueOf(contactId)}, null);
while(c.moveToNext()){
int type = c.getInt(c.getColumnIndex(Phone.TYPE));
..
}
try this:
int type = mCursor.getInt(mCursor.getColumnIndex(Phone.TYPE));
the "type" value will be 1,2,3 or 4 where
TYPE_HOME = 1;
TYPE_MOBILE = 2;
TYPE_WORK = 3;
TYPE_OTHER = 7;
Ok finally i completed the task.here my code
String mobile = "";
String home="";
String work="";
String fax="";
String other="";
String disName="";
String pName="";
String fName="";
String lName="";
String sName="";
String mName="";
String postBox="";
String streat="";
String country="";
String emailAdd="";
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null, null, null);
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
disName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
///*
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + id, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
System.out.println("Numeber= "+number);
switch (type) {
case Phone.TYPE_HOME:
home=number;
break;
case Phone.TYPE_MOBILE:
mobile=number;
break;
case Phone.TYPE_WORK:
work=number;
break;
case Phone.TYPE_OTHER:
other=number;
break;
case Phone.TYPE_FAX_HOME:
fax=number;
break;
case Phone.TYPE_FAX_WORK:
fax=number;
break;
}
}
phones.close();
Cursor name = cr.query(Data.CONTENT_URI, null,
Data.CONTACT_ID + " ="+id +" AND "+Data.MIMETYPE+"='"+StructuredName.CONTENT_ITEM_TYPE+"'", null, null);
while(name.moveToNext()){
sName=name.getString(name.getColumnIndex(StructuredName.PREFIX));
fName=name.getString(name.getColumnIndex(StructuredName.GIVEN_NAME));
mName=name.getString(name.getColumnIndex(StructuredName.MIDDLE_NAME));
lName=name.getString(name.getColumnIndex(StructuredName.FAMILY_NAME));
sName=name.getString(name.getColumnIndex(StructuredName.SUFFIX));
System.out.println(mName);
}
Cursor address = cr.query(Data.CONTENT_URI, null,
Data.CONTACT_ID + " ="+id +" AND "+Data.MIMETYPE+"='"+StructuredPostal.CONTENT_ITEM_TYPE+"'", null, null);
while(address.moveToNext()){
postBox=address.getString(address.getColumnIndex(StructuredPostal.POBOX));
streat=address.getString(address.getColumnIndex(StructuredPostal.STREET));
mName=address.getString(address.getColumnIndex(StructuredPostal.COUNTRY));
System.out.println(postBox);
}
Cursor email = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
Data.CONTACT_ID + " ="+id , null, null);
while(email.moveToNext()){
emailAdd=email.getString(email.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
In where clause of your query use Phone.TYPE_HOME.. this will give you the desired nor..

Categories

Resources