Cannot resolve method 'managedQuery" - android

I have a stand alone app that pulls up the phone number of a contact and fills it into a text box. This works fine as an activity, but when I put the same code into a fragment, I get an error that it cannot resolve the method 'managedQuerry'. I also get the message for getContentResover().
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor cur = managedQuery(contactData, null, null, null, null);
ContentResolver contect_resolver = getContentResolver();
if (cur.moveToFirst()) {
String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String name = "";
String no = "";
Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
if (phoneCur.moveToFirst()) {
name = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
no = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
Log.e("Phone no & name :***: ", name + " : " + no);
//txt.append(name + " : " + no + "\n");
editPhoneNum.setText(no);
id = null;
name = null;
no = null;
phoneCur = null;
}
contect_resolver = null;
cur = null;
// populateContacts();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.e("IllegalArgException :: ", e.toString());
} catch (Exception e) {
e.printStackTrace();
Log.e("Error :: ", e.toString());
}
}

If you're Using managedQuery in Fragment, please use getActivity() before managedQuery
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);

I had the same problem as you.
This is a dialog of my project that get contacts information and show them
private void contactsdialog() {
final Dialog dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.contactsdialog);
ListView contacts_list = (ListView)dialog.findViewById(R.id.listView);
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_ID
};
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cursor =dialog.getContext().getContentResolver().query(uri, projection, null, null, sortOrder);
ArrayList<String> columnArray1 = new ArrayList<String>();
ArrayList<String> columnArray2 = new ArrayList<String>();
while (cursor.moveToNext()) {
try {
columnArray2.add(cursor.getString(0));
columnArray1.add(cursor.getString(1));
} catch(Exception e) {
// Log.d("error",e.toString());
}
}
cursor.close();
String[] colStrArr1 = (String[]) columnArray1.toArray(new String[columnArray1.size()]);
String[] colStrArr2 = (String[]) columnArray2.toArray(new String[columnArray1.size()]);
contactadapter adapter = new contactadapter(getActivity(),colStrArr1,colStrArr2);
contacts_list.setAdapter(adapter);
dialog.show();
}
As you can see, I didn't use managedquery, because it's deprecated. Instead I used "getContentResolver().query" that is the same as managedquery. Also you need a dialog name like "dialog in my codes" to bound getContentResolver().query with it (because its not on a activity and my main class is fragment like your case). And sorry for bad English

Related

How to retrieve company name from the selected contact

Using ContactsContract I am able to retrieve and display selected mobile number and the relevant contact name.
But instead of returning the company name it's returning the mobile number again.
The intent I use to select a specific phone number when there are multiple numbers
Intent calContctPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
calContctPickerIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(calContctPickerIntent, 1);
here is the main code
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (1):
if (resultCode == Activity.RESULT_OK) {
Uri contctDataVar = data.getData();
Cursor contctCursorVar = getContentResolver().query(contctDataVar, null, null, null, null);
if (contctCursorVar.getCount() > 0) {
while (contctCursorVar.moveToNext()) {
String ContctUidVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts._ID));
String ContctNamVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String Companyname = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
Log.i("Names", ContctNamVar);
if (Integer.parseInt(contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Query phone here. Covered next
String ContctMobVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String Companyname2 = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
mobile.setText(ContctMobVar);
custname.setText(ContctNamVar);
companyname.setText(Companyname2);
Log.i("Number", ContctMobVar);
}
}
}
}
break;
}
}
I need to find a way to retrieve the company name saved under the selected contact.
You may try something like this :
ContentResolver mContentResolver = this.getContentResolver();
Cursor contacts = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
String mContactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
String mRawContactId = getRawContactID(mContactId);
String mCompanyName = getCompanyName(mRawContactId);
private String getRawContactID(String contactId) {
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{contactId};
Cursor c = mContentResolver.query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (c == null) return null;
int rawContactId = -1;
if (c.moveToFirst()) {
rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
}
c.close();
return String.valueOf(rawContactId);
}
private String getCompanyName(String rawContactId) {
try {
String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{rawContactId,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor cursor = mContentResolver.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (cursor == null) return null;
String name = null;
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
}
cursor.close();
return name;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
With the help of the solution provided by #Shiva Snape I was able to solve the problem.
Code for button to call contacts app and select the relevant number
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
Code to collect Contact Number, Name and company name.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
null, null, null);
ContentResolver mContentResolver = this.getContentResolver();
if (c != null && c.moveToFirst()) {
String number = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String name = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String contactId = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String rawContactId = getRawContactId(contactId);
String companyName = getCompanyName(rawContactId);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
private String getCompanyName(String rawContactId) {
try {
String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{rawContactId,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (cursor == null) return null;
String Vname = null;
if (cursor.moveToFirst()) {
Vname = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
}
cursor.close();
return Vname;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private String getRawContactId(String contactId) {
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{contactId};
Cursor c = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (c == null) return null;
int rawContactId = -1;
if (c.moveToFirst()) {
rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
}
c.close();
return String.valueOf(rawContactId);
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
}
}
Thanks to the Stack Overflow community for helping me out. Hope this becomes helpful to others.

fetching multiple contacts from phone book and display

The problem which i'm facing is I am not able to display the fetched value, as I have used a list view to display the values are not reaching it. This is my code snippet which fetches multiple contacts from phone book. Hope any1 help me solve it.
private void chooseContact() {
Intent phonebookIntent = new Intent("intent.action.INTERACTION_TOPMENU");
phonebookIntent.putExtra("additional", "phone-multi");
phonebookIntent.putExtra("maxRecipientCount", MAX_PICK_CONTACT);
phonebookIntent.putExtra("FromMMS", true);
startActivityForResult(phonebookIntent, REQUEST_CODE_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == RESULT_PICK_CONTACT) {
Uri contractData = data.getData();
ContactRetriever cr = new ContactRetriever(getApplicationContext(), contractData);
Person p = cr.getPerson();
if (p == null)
Toast.makeText(this, "Phone number not found!", Toast.LENGTH_SHORT).show();
else {
PersonManager.savePerson(p, getApplicationContext());
listContacts.setAdapter(new PersonAdapter(this, PersonManager.getSavedPersons(this)));
}
}
}
}}
And the Uri value is called and used in next below class
public class ContactRetriever {
private final String TAG = "ContactRetriever";
private ContentResolver cr;
private Context context;
private Uri contractData;
private String id;
public ContactRetriever(Context context,Uri contractData ) {
this.context = context;
this.cr = context.getContentResolver();
this.contractData = contractData;
}
public Person getPerson() {
String name = getName();
String num = getNumber();
if (name != null && num != null)
return new Person(getNumber(), getName());
else return null;
}
private String getNumber() {
String ret = null;
Cursor cId = cr.query(contractData, new String[]{ContactsContract.Contacts._ID}, null, null, null);
if (cId.moveToFirst()){
id = cId.getString(cId.getColumnIndex(ContactsContract.Contacts._ID));
Log.i(TAG + " IDs: ", id);
}
cId.close();
Cursor cNum = cr.query(contractData, null, null, null, null);
if (cNum.moveToNext()){
ret = cNum.getString(cNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i(ret, TAG + " NUMBERS: ");
}
return ret;
}
private String getName() {
String ret = null;
Cursor c = cr.query(contractData, null, null, null, null);
if (c.moveToFirst())
ret = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
c.close();
Log.i(TAG + "NAMES: ", ret);
return ret;
}
}
Here is my working code for mine
//enter code here
private void getAllContacts() {
List<InviteContactInfo> inviteContactList = new ArrayList();
InviteContactInfo inviteContactInfo;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
inviteContactInfo = new InviteContactInfo();
inviteContactInfo.setContactName(name);
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id},
null);
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
inviteContactInfo.setContactNumber(phoneNumber);
}
phoneCursor.close();
Cursor emailCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCursor.moveToNext()) {
String emailId = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
Bitmap photo =null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
inviteContactInfo.setContactImage(photo);
}
else
{
photo =BitmapFactory.decodeResource(getResources(), R.drawable.profilepic);;
inviteContactInfo.setContactImage(photo);
}
assert inputStream != null;
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
inviteContactList.add(inviteContactInfo);
}
}
InviteContactAdapter contactAdapter = new InviteContactAdapter(getApplicationContext(), inviteContactList);
recList.setLayoutManager(new LinearLayoutManager(this));
recList.setAdapter(contactAdapter);
}
}

How to get Email address from device contact in android?

I need to get the Email address from device contacts.
I have tried this to get email address.
Cursor cur1 = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[] { device_contactId }, null);
But the above code not working.
I am inserting email using below code.
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, emailArr[i])
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, _emailType)
.build());
Please help me out.
Suggestions appreciated.
Thanks kind regards.
This is the code for getting email address from selected contact
public void doLaunchContactPicker(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
switch (requestCode)
{
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String email = "", name = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: " + result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Email.CONTENT_URI, null, Email.CONTACT_ID + "=?", new String[] { id }, null);
int nameId = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
int emailIdx = cursor.getColumnIndex(Email.DATA);
// let's just get the first email
if (cursor.moveToFirst()) {
email = cursor.getString(emailIdx);
name = cursor.getString(nameId);
Log.v(DEBUG_TAG, "Got email: " + email);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText emailEntry = (EditText) findViewById(R.id.editTextv);
EditText personEntry = (EditText) findViewById(R.id.person);
emailEntry.setText(email);
personEntry.setText(name);
if (email.length() == 0 && name.length() == 0)
{
Toast.makeText(this, "No Email for Selected Contact",Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
doLaunchContactPicker is an onclick of Button
To return an arraylist of names which has email id use this code.
public ArrayList<String> getNameEmailDetails(){
ArrayList<String> names = new ArrayList<String>();
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));
Cursor cur1 = cr.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){
names.add(name);
}
}
cur1.close();
}
}
return names;
}
Dont forget to add
<uses-permission android:name="android.permission.READ_CONTACTS" />
in AndroidManifest.xml
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String hasNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String email = "";
if (Integer.valueOf(hasNumber) == 1) {
Cursor numbers = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (numbers.moveToNext()) {
email = numbers.getString(numbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
if(getEmail(email).isEmpty()){
Toast.makeText(this, "Email Not Found In That Contact Try Another", Toast.LENGTH_SHORT).show();
}
else {
edt_email_contact.setText("" + getEmail(email));
} }
}
}
break;
}

Fetching contacts in android is very slow

I had written a code to fetch contact name, phone number and image from Contacts and to display it on a listview in android. It's working fine but taking more time to load. I had tried to use multi-threading in some parts of the code. But the loading time is not decreased.
Here is the onCreate() method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvDetail = (ListView) findViewById(R.id.listView1);
fetchcontacts();
lvDetail.setAdapter(new MyBaseAdapter(context, myList));
}
Here is the code for fetch contacts:
private void fetchcontacts() {
// TODO Auto-generated method stub
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
int count = cursor.getCount();
if (count > 0) {
Toast.makeText(context, "count >0", Toast.LENGTH_SHORT).show();
while (cursor.moveToNext()) {
String columnId = ContactsContract.Contacts._ID;
int cursorIndex = cursor.getColumnIndex(columnId);
String id = cursor.getString(cursorIndex);
name = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Toast.makeText(context, "Toast 1", Toast.LENGTH_SHORT).show();
int numCount = Integer.parseInt(cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (numCount > 0) {
Toast.makeText(context, "Toast 2", Toast.LENGTH_SHORT).show();
Cursor phoneCursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
CommonDataKinds.Phone.CONTACT_ID+" = ?", new String[] { id
}, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
while (phoneCursor.moveToNext()) {
Toast.makeText(context, "Toast 3", Toast.LENGTH_SHORT).show();
phoneNo = phoneCursor.getString(phoneCursor
.getColumnIndex(ContactsContract.CommonDataKinds.
Phone.NUMBER));
String image_uri = phoneCursor
.getString(phoneCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (image_uri != null) {
Toast.makeText(context, "Toast 4", Toast.LENGTH_SHORT).show();
System.out.println(Uri.parse(image_uri));
try {
bitmap = MediaStore.Images.Media
.getBitmap(this.getContentResolver(),
Uri.parse(image_uri));
// sb.append("\n Image in Bitmap:" + bitmap);
// System.out.println(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
getDataInList(name,phoneNo,bitmap);
name=null;
phoneNo=null;
Drawable myDrawable = getResources().getDrawable(R.drawable.star1);
bitmap = ((BitmapDrawable) myDrawable).getBitmap();
}
phoneCursor.close();
}
}
}
Here the setAdapter() function of the listview is working after fetching all the contacts to an ArrayList. do anyone have idea about how to display the contacts during fetching contacts? any sample code?
1.Read the Columns from the Cursor which you required only ,According to your requirement you just need _ID,HAS_PHONE_NUMBER,DISPLAY_NAME ,so change the Cursor reading
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts.DISPLAY_NAME }, null, null,
ContactsContract.Contacts.DISPLAY_NAME + " ASC");
2.Dont do the time taking process in the UI thread..Use AsyncTask instead
Note : This two steps will resolve to some extent..but not completely
I made it by reduce repeated query wich is expensive. Best of my solution is that method found all mobile phones and email for each contact and insert to list for every contact values. It is fast as storm now :)
//contact entity
public class MobileContact {
public String name;
public String contact;
public Type type;
public MobileContact(String contact, Type type) {
name = "";
this.contact = contact;
this.type = type;
}
public MobileContact(String name, String contact, Type type) {
this.name = name;
this.contact = contact;
this.type = type;
}
public enum Type {
EMAIL, PHONE
}
#Override
public String toString() {
return "MobileContact{" +
"name='" + name + '\'' +
", contact='" + contact + '\'' +
", type=" + type +
'}';
}
}
// method for collect contacts
public List<MobileContact> getAllContacts() {
log.debug("get all contacts");
List<MobileContact> mobileContacts = new ArrayList<>();
ContentResolver contentResolver = context.getContentResolver();
// add all mobiles contact
Cursor phonesCursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.CONTACT_ID}, null, null, null);
while (phonesCursor != null && phonesCursor.moveToNext()) {
String contactId = phonesCursor.getString(phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String phoneNumber = phonesCursor.getString(phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replace(" ", "");
mobileContacts.add(new MobileContact(contactId, phoneNumber, MobileContact.Type.PHONE));
}
if (phonesCursor != null) {
phonesCursor.close();
}
// add all email contact
Cursor emailCursor = contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Email.DATA, ContactsContract.CommonDataKinds.Email.CONTACT_ID}, null, null, null);
while (emailCursor != null && emailCursor.moveToNext()) {
String contactId = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID));
String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
mobileContacts.add(new MobileContact(contactId, email, MobileContact.Type.EMAIL));
}
if (emailCursor != null) {
emailCursor.close();
}
// get contact name map
Map<String, String> contactMap = new HashMap<>();
Cursor contactsCursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER}, null, null, ContactsContract.Contacts.DISPLAY_NAME);
while (contactsCursor != null && contactsCursor.moveToNext()) {
String contactId = contactsCursor.getString(contactsCursor.getColumnIndex(ContactsContract.Contacts._ID));
String contactName = contactsCursor.getString(contactsCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contactMap.put(contactId, contactName);
}
if (phonesCursor != null) {
phonesCursor.close();
}
// replace contactId to display name
for (MobileContact mobileContact : mobileContacts) {
String displayName = contactMap.get(mobileContact.name);
mobileContact.name = displayName != null ? displayName : "";
}
// sort list by name
Collections.sort(mobileContacts, new Comparator<MobileContact>() {
#Override
public int compare(MobileContact c1, MobileContact c2) {
return c1.name.compareTo(c2.name);
}
});
return mobileContacts;
}
The contacts in larse size use in backround task.
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number[i]));
ContentResolver contentResolver = getContentResolver();
Cursor search = contentResolver.query(uri, new String[]{ContactsContract.PhoneLookup._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
try {
if (search != null && search.getCount() > 0) {
search.moveToNext();
name = search.getString(search.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
id = search.getString(search.getColumnIndex(ContactsContract.Data._ID));
System.out.println("name" + name + "id" + id);
/* tv_name.setText(name);
tv_id.setText(id);
tv_phone.setText(number);*/
}
} finally {
if (search != null) {
search.close();
}
}
Fastest way for me soo far .
ContentResolver cr = mContext.getContentResolver(); Cursor cursor= mContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, "HAS_PHONE_NUMBER <> 0", null, null); if (cursor!= null) { final int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); final int numberIndex = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER); final int idIndex= cursor.getColumnIndex(ContactsContract.Contacts._ID); String displayName, number = null, idValue; while (cursor.moveToNext()) {
displayName = cursor.getString(displayNameIndex);
idValue= cursor.getString(idIndex);
Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, "contact_id = '" + idValue + "'", null, null);
phones.moveToFirst();
try {
number = phones.getString(phones.getColumnIndex("data1"));
}
catch (CursorIndexOutOfBoundsException e)
{`
}
phones.close();
userList.add(new ContactModel(displayName , number , null , }

Access contacts and get email address

I have a code snippet for accessing to Contacts. When user click the button then the contacts list will be open and user can choose a person from contacts and the person's email address should be write on a edittext. I can receive the email from the persons which user select. But I can't set it to the edittext.
static String email = "";
imgbtnaddfromcontacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (v == imgbtnaddfromcontacts) {
try
{
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1);
} catch (Exception e) {
e.printStackTrace();
Log.e("Error in intent : ", e.toString());
}
}
}
});
kimeTxt.setText(email);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK) {
// Get data
Uri contactData = data.getData();
// Cursor
Cursor cur = managedQuery(contactData, null, null, null, null);
ContentResolver contect_resolver = getContentResolver();
// List
if (cur.moveToFirst()) {
String id = cur
.getString(cur
.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
Cursor phoneCur = contect_resolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
Cursor emailCur = contect_resolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[] { id }, null);
if (phoneCur.moveToFirst()) {
name = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
no = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
email = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if (email != null)
{
seciliEmail = email;
} else {
Toast.makeText(EpostaIletActivity.this,
"Kişinin eposta hesabı bulunmamaktadır.",
Toast.LENGTH_SHORT);
Log.w("Error: ", "Kişinin eposta hesabı yok.");
}
}
Log.e("Phone no & name & email :***: ", name + " : " + no + ":" + email);
// txt.append(name + " : " + no + "\n");
id = null;
name = null;
no = null;
seciliEmail = "xxx";
phoneCur = null;
emailCur.close();
}
contect_resolver = null;
cur = null;
// populateContacts();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.e("IllegalArgumentException :: ", e.toString());
} catch (Exception e) {
e.printStackTrace();
Log.e("Error :: ", e.toString());
}
}
Am using below code for getting email address from selected contact -
public void doLaunchContactPicker(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
switch (requestCode)
{
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String email = "", name = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: " + result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Email.CONTENT_URI, null, Email.CONTACT_ID + "=?", new String[] { id }, null);
int nameId = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
int emailIdx = cursor.getColumnIndex(Email.DATA);
// let's just get the first email
if (cursor.moveToFirst()) {
email = cursor.getString(emailIdx);
name = cursor.getString(nameId);
Log.v(DEBUG_TAG, "Got email: " + email);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText emailEntry = (EditText) findViewById(R.id.editTextv);
EditText personEntry = (EditText) findViewById(R.id.person);
emailEntry.setText(email);
personEntry.setText(name);
if (email.length() == 0 && name.length() == 0)
{
Toast.makeText(this, "No Email for Selected Contact",Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
doLaunchContactPicker is an onclick of Button Use the code wherever you wants.
make sure your app has got permission, otherwise you'll get weird Exceptions
in AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_CONTACTS" />
You can achieve it like this
public class Abc extends Activity{
EditText kimeTxt;
Intent i;
Bundle b ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_course);
kimeTxt= (EditText)findViewById(R.id.emailid);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK) {
// Get data
Uri contactData = data.getData();
// Cursor
Cursor cur = managedQuery(contactData, null, null, null, null);
ContentResolver contect_resolver = getContentResolver();
// List
if (cur.moveToFirst()) {
String id = cur
.getString(cur
.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
Cursor phoneCur = contect_resolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
Cursor emailCur = contect_resolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[] { id }, null);
if (phoneCur.moveToFirst()) {
name = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
no = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
email = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if (email != null)
{
seciliEmail = email;
} else {
Toast.makeText(EpostaIletActivity.this,
"Kişinin eposta hesabı bulunmamaktadır.",
Toast.LENGTH_SHORT);
Log.w("Error: ", "Kişinin eposta hesabı yok.");
}
}
Log.e("Phone no & name & email :***: ", name + " : " + no + ":" + email);
// txt.append(name + " : " + no + "\n");
id = null;
name = null;
no = null;
seciliEmail = "xxx";
phoneCur = null;
emailCur.close();
}
// can set email id here
kimeTxt.setText(email);
contect_resolver = null;
cur = null;
// populateContacts();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.e("IllegalArgumentException :: ", e.toString());
} catch (Exception e) {
e.printStackTrace();
Log.e("Error :: ", e.toString());
}
}

Categories

Resources