Phonegap Android Contact Picker Plugin (updating a plugin) - android

In my PhoneGap app, I am trying to get the native Android contact picker to launch so I can fetch some phone numbers.
I researched online and couldn't find much until I saw the ContactView plugin:
https://github.com/phonegap/phonegap-plugins/tree/master/Android/ContactView
When I set up the plugin according to the instructions, I encountered errors everywhere in its ContactView.java file. It seems that it is using a very old version of the plugin structure with ctx and other deprecated commands (e.g. startActivityForResult).
So I tried to convert it into a modern plugin by going through it line by line but I was too n00b and got stuck at about line 40 (inside the startContactActivity function). This is what I have so far:
package com.rearden;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;
public class ContactView extends CordovaPlugin {
private static final String TAG = "PickContactPlugin";
private static final int PICK_CONTACT = 1;
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
Log.d(TAG, "Inside ContactView plugin.");
JSONObject result = new JSONObject();
if (action.equals("") || action.equals("ContactView")) {
return startContactActivity();
} else {
Log.e(TAG, "Unknown action provided.");
result.put("error", "Unknown action provided.");
callbackContext.success(result);
return false;
}
}
public boolean startContactActivity() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
//STUCK HERE
this.cordova.getActivity().startActivityForResult((Plugin) this, intent, PICK_CONTACT);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
String name = null;
String number = null;
String email = null;
ContentResolver contentResolver = cordova.getActivity().getContentResolver();
switch (reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = contentResolver.query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String ContactID = c.getString(c
.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(hasPhone) == 1) {
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ "='" + ContactID + "'", null,
null);
while (phoneCursor.moveToNext()) {
number = phoneCursor
.getString(phoneCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}
// get email address
Cursor emailCur = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + "='" + ContactID + "'", null,null);
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));
//String emailType = emailCur.getString(
// emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
emailCur.close();
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
JSONObject contactObject = new JSONObject();
try {
contactObject.put("name", name);
contactObject.put("phone", number);
contactObject.put("email", email);
} catch (JSONException e) {
e.printStackTrace();
}
this.success(new PluginResult(PluginResult.Status.OK,
contactObject), this.callback);
}
}
break;
}
}
}
What I don't seem to be able to do is to find an equivalent for the "this.ctx.startActivityForResult" function.
I've already spent an entire day on this and it's starting to seem excessive, so I turn to you guys for help. Can it really be that hard to access the native contact picker?

The equivalent is this.ctx.getActivity().getContentResolver().query
The code below works in cordova 2.6.
package com.rearden;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.apache.cordova.api.PluginResult.Status;
import android.util.Log;
public class ContactViewPlugin extends Plugin {
private static final int PICK_CONTACT = 1;
private String callback;
#Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
startContactActivity();
PluginResult mPlugin = new PluginResult(PluginResult.Status.NO_RESULT);
mPlugin.setKeepCallback(true);
this.callback = callbackId;
return mPlugin;
}
public void startContactActivity() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
this.ctx.startActivityForResult((Plugin) this, intent, PICK_CONTACT);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
String name = null;
String number = null;
String email = null;
switch (reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = this.ctx.getActivity().getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String ContactID = c.getString(c
.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(hasPhone) == 1) {
Cursor phoneCursor = this.ctx.getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ "='" + ContactID + "'", null,
null);
while (phoneCursor.moveToNext()) {
number = phoneCursor
.getString(phoneCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}
// get email address
Cursor emailCur = this.ctx.getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + "='" + ContactID + "'", null,null);
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));
//String emailType = emailCur.getString(
// emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
emailCur.close();
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
JSONObject contactObject = new JSONObject();
try {
contactObject.put("name", name);
contactObject.put("phone", number);
contactObject.put("email", email);
} catch (JSONException e) {
e.printStackTrace();
}
this.success(new PluginResult(PluginResult.Status.OK,
contactObject), this.callback);
}
}
break;
}
}
}
I also changed the JS file.
var ContactViewPlugin = function() {
};
ContactViewPlugin.prototype.show = function(successCallback, failureCallback) {
console.log('calling *** show');
return cordova.exec(successCallback,
failureCallback,
'ContactViewPlugin',
'show',
[]);
};
if(!window.plugins) {
window.plugins = {};
}
if (!window.plugins.contactViewPlugin) {
window.plugins.contactViewPlugin = new ContactViewPlugin();
}
Do not forget to add the plugin to the config.xml list.

in cordova 3.0.0
this worked for me
this.cordova.startActivityForResult((CordovaPlugin) this, intent, PICK_CONTACT);

Related

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

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

How to get photo of the contact in Android?

I'm simply getting the all contact list to an object (PhoneBookContact):
private static final Uri PURI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
private static final String PID = ContactsContract.CommonDataKinds.Phone._ID;
private static final String PNAME = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
private static final String PNUM = ContactsContract.CommonDataKinds.Phone.NUMBER;
String[] projection = new String[]{PID, PNAME, PNUM};
String sortOrder = PNAME + " COLLATE LOCALIZED ASC";
Cursor people = mContext.getContentResolver().query(PURI, projection, null, null, sortOrder);
int indexid = people.getColumnIndex(PID);
int indexName = people.getColumnIndex(PNAME);
int indexNumber = people.getColumnIndex(PNUM);
people.moveToFirst();
do {
PhoneBookContact phoneBookContact = new PhoneBookContact();
phoneBookContact.setmCursorId(people.getLong(indexid));
phoneBookContact.setmDisplayName(people.getString(indexName));
phoneBookContact.setmPhoneNumber(UriFactory.formatNumberToInternational(people.getString(indexNumber)));
phoneList.put(phoneBookContact.getmPhoneNumber(), phoneBookContact);
} while (people.moveToNext());
people.close();
To fetch the photo of the user from Android Contacts, I'am using this method:
public static Uri loadContactPhotoUri(ContentResolver contentResolver, long id) {
try {
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
return person;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
Finally, this code gives this URI for a specific user:
content://com.android.contacts/contacts/5907
Since I'm calling this URI with ContactsContract.CommonDataKinds.Phone._ID id, I can't get the photo of the user successfully. In fact, it should be the id of ContactsContract.Contacts._ID. How can I query the photo of the user and fix this problem?
Instead of ContactsContract.CommonDataKinds.Phone._ID, you must use ContactsContract.CommonDataKinds.Phone.CONTACT_ID to save the cursorID of Contacts table. It solved my problem.
This file have funtion get contact photo
https://github.com/heinrisch/Contact-Picture-Sync/blob/master/src/heinrisch/contact/picture/sync/ContactHandler.java
package heinrisch.contact.picture.sync;
import java.io.InputStream;
import java.util.ArrayList;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDiskIOException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts.Data;
import android.provider.ContactsContract.RawContacts;
import android.util.Log;
public class ContactHandler {
public static ArrayList<String> getNumbers(String ID, Context context){
ArrayList<String> numbers = new ArrayList<String>();
ContentResolver cr = context.getContentResolver();
Cursor phones = cr.query(Phone.CONTENT_URI, null,Phone.CONTACT_ID + " = " + ID, null, null);
while (phones.moveToNext()) {
numbers.add(phones.getString(phones.getColumnIndex(Phone.NUMBER)));
}
phones.close();
return numbers;
}
public static void matchContactsToFriends(ArrayList<Friend> friends, Context context) {
Cursor people = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(people == null){
Log.e("ContactHandler", "Could not find contacts...?");
return;
}
while(people.moveToNext()) {
String ID = null,name = null;
int columnIndex = people.getColumnIndex(ContactsContract.Contacts._ID);
if(columnIndex != -1) ID = people.getString(columnIndex);
columnIndex = people.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
if(columnIndex != -1) name = people.getString(columnIndex);
//ArrayList<String> numbers = getNumbers(ID,context); //"can't" get this from facebook
if(name == null) continue;
for(Friend f : friends){
if(f.isMatchedWithContact()) continue;
if(f.getName().equals(name)){
f.setContactID(ID);
Bitmap contactPhoto = getPhoto(context, ID);
if(contactPhoto != null) f.setContactPicture(contactPhoto);
break;
}
}
}
people.close();
}
public static void setContactPicture(Friend f, Context context){
f.setContactPicture(getPhoto(context, f.getContactID()));
}
public static int getNumberOfContacts(Context context) {
Cursor people = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
int numberOfContacts = people.getCount();
people.close();
return numberOfContacts;
}
public static Uri getPicture(Context context, String ID){
ContentResolver cr = context.getContentResolver();
Uri rawContactUri = null;
Cursor rawContactCursor = cr.query(RawContacts.CONTENT_URI, new String[] {RawContacts._ID}, RawContacts.CONTACT_ID + " = " + ID, null, null);
if(!rawContactCursor.isAfterLast()) {
rawContactCursor.moveToFirst();
rawContactUri = RawContacts.CONTENT_URI.buildUpon().appendPath(""+rawContactCursor.getLong(0)).build();
}
rawContactCursor.close();
return rawContactUri;
}
public static void setContactPicture(Context context, String ID, Bitmap picture){
ContentResolver cr = context.getContentResolver();
Uri rawContactUri = getPicture(context, ID);
if(rawContactUri == null){
Log.e("rawContactUri", "is null");
return;
}
ContentValues values = new ContentValues();
int photoRow = -1;
String where = ContactsContract.Data.RAW_CONTACT_ID + " == " +
ContentUris.parseId(rawContactUri) + " AND " + Data.MIMETYPE + "=='" +
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI, null, where, 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, Tools.bitmapToByteArray(picture));
values.put(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
try{
if(photoRow >= 0){
cr.update(
ContactsContract.Data.CONTENT_URI,
values,
ContactsContract.Data._ID + " = " + photoRow, null);
} else {
cr.insert(
ContactsContract.Data.CONTENT_URI,
values);
}
}catch(SQLiteDiskIOException dIOe){
//TODO: should show this to the user..
dIOe.printStackTrace();
}
}
public static Bitmap getPhoto(Context context, String contactId) {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId));
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), uri);
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
}

showing send_invitations.class cant be resolved to a type in android

hai all.....
I am displying all my emulator contacts into my appliaction.I want to select some of the contacts and putting into an array...I followed the below code ...please help me..
package com.android.sample;
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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class selectedcontacts extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button existing_contacts = (Button)findViewById(R.id.btn_contact_existing);
existing_contacts.setOnClickListener(new OnClickListener() {
public void onClick(View v){
Intent intent_contacts = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
/*contacts.setAction(android.content.Intent.ACTION_VIEW);
contacts.setData(People.CONTENT_URI);*/
startActivityForResult(intent_contacts, 0);
//displayContacts();
}
});
}
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
String name,mailid,id;
switch(requestCode)
{
case 0:
{
if(resultCode == RESULT_OK )
{
Uri contactdata = data.getData();
Cursor cur = managedQuery(contactdata, null, null, null, null);
if(cur.moveToFirst())
{
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emailCur = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",new String[]{id}, null);
emailCur.moveToFirst();
String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
name = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//mailid = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
//mailid = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Email._ID));
// Toast.makeText(context_contact, "Name:"+name+"\nmailid:"+email, Toast.LENGTH_SHORT).show();
Intent intent_add_invitees = new Intent(Contact.this,Send_invitations.class);
intent_add_invitees.putExtra("invitee_name", name);
intent_add_invitees.putExtra("invitee_mailid", email);
setResult(RESULT_OK, intent_add_invitees);
finish();
}
}
}
}
}
}
anyone show me the way how to get selected contacts(using checkbox) into an array
See my answer to the post
public static void getContactNumbers(Context context) {
String contactNumber = null;
int contactNumberType = Phone.TYPE_MOBILE;
String nameOfContact = null;
if (ApplicationConstants.phoneContacts.size() <= 0) {
ContentResolver cr = context.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur
.getColumnIndex(BaseColumns._ID));
nameOfContact = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phones = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
while (phones.moveToNext()) {
contactNumber = phones.getString(phones
.getColumnIndex(Phone.NUMBER));
contactNumberType = phones.getInt(phones
.getColumnIndex(Phone.TYPE));
Log.i(TAG, "...Contact Name ...." + nameOfContact
+ "...contact Number..." + contactNumber);
}
phones.close();
}
}
}// end of contact name cursor
cur.close();
}
}
Thanks
Deepak

contacts picker, retrieving last name, first name, phone number

Right now, I'm able to retrieve the phone number and set the text of my editText to that number. But when I try to get the last name or first name it doesn't work. Note the stuff I commented out.
Heres my code:
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.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class main extends Activity {
private static final int CONTACT_PICKER_RESULT = 1001;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button getContacts = (Button)findViewById(R.id.getContacts);
getContacts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(i, CONTACT_PICKER_RESULT);
}
});
}
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if(resultCode == RESULT_OK) {
switch (reqCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String number = "";
String lastName ="";
try {
Uri result = data.getData();
//get the id from the uri
String id = result.getLastPathSegment();
//query
cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone._ID + " = ? " , new String[] {id}, null);
// cursor = getContentResolver().query(Phone.CONTENT_URI,
// null, Phone.CONTACT_ID + "=?", new String[] { id },
// null);
int numberIdx = cursor.getColumnIndex(Phone.DATA);
if(cursor.moveToFirst()) {
number = cursor.getString(numberIdx);
//lastName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
} else {
//WE FAILED
}
} catch (Exception e) {
//failed
} finally {
if (cursor!=null) {
cursor.close();
}
EditText numberEditText = (EditText)findViewById(R.id.number);
numberEditText.setText(number);
//EditText lastNameEditText = (EditText)findViewById(R.id.last_name);
//lastNameEditText.setText(lastName);
}
}
}
This is how i got the display name...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
try {
Uri result = data.getData();
String id = result.getLastPathSegment();
//Get Name
cursor = getContentResolver().query(result, null, null, null, null);
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
} catch (Exception e) { }
}
}
}
Hope it helps :)
If you have your contact id, you can use this method for retrieving all the other contact data:
Map<String, String> result = new HashMap<>();
Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.CONTACT_ID + "='" + YOUR_CONTACT_ID + "'", null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String mime = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
switch (mime) {
case ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE:
result.put(FIRST_NAME, cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME)));
result.put(LAST_NAME, cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME)));
break;
case ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE:
result.put(CITY, cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY)));
result.put(STREET, cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET)));
result.put(ZIP, cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE)));
break;
case ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE:
if (ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE == cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))) {
result.put(MOBILE, cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
break;
}
}
cursor.close();
}
return result;

How to call Android contacts list?

I'm making an Android app, and need to call the phone's contact list. I need to call the contacts list function, pick a contact, then return to my app with the contact's name. Here's the code I got on the internet, but it doesnt work.
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class Contacts extends ListActivity {
private ListAdapter mAdapter;
public TextView pbContact;
public static String PBCONTACT;
public static final int ACTIVITY_EDIT=1;
private static final int ACTIVITY_CREATE=0;
// Called when the activity is first created.
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Cursor C = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
startManagingCursor(C);
String[] columns = new String[] {People.NAME};
int[] names = new int[] {R.id.row_entry};
mAdapter = new SimpleCursorAdapter(this, R.layout.mycontacts, C, columns, names);
setListAdapter(mAdapter);
} // end onCreate()
// Called when contact is pressed
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor C = (Cursor) mAdapter.getItem(position);
PBCONTACT = C.getString(C.getColumnIndex(People.NAME));
// RHS 05/06
//pbContact = (TextView) findViewById(R.id.myContact);
//pbContact.setText(new StringBuilder().append("b"));
Intent i = new Intent(this, NoteEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
}
I'm not 100% sure what your sample code is supposed to do, but the following snippet should help you 'call the contacts list function, pick a contact, then return to [your] app with the contact's name'.
There are three steps to this process.
1. Permissions
Add a permission to read contacts data to your application manifest.
<uses-permission android:name="android.permission.READ_CONTACTS"/>
2. Calling the Contact Picker
Within your Activity, create an Intent that asks the system to find an Activity that can perform a PICK action from the items in the Contacts URI.
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
Call startActivityForResult, passing in this Intent (and a request code integer, PICK_CONTACT in this example). This will cause Android to launch an Activity that's registered to support ACTION_PICK on the People.CONTENT_URI, then return to this Activity when the selection is made (or canceled).
startActivityForResult(intent, PICK_CONTACT);
3. Listening for the Result
Also in your Activity, override the onActivityResult method to listen for the return from the 'select a contact' Activity you launched in step 2. You should check that the returned request code matches the value you're expecting, and that the result code is RESULT_OK.
You can get the URI of the selected contact by calling getData() on the data Intent parameter. To get the name of the selected contact you need to use that URI to create a new query and extract the name from the returned cursor.
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// TODO Whatever you want to do with the selected contact name.
}
}
break;
}
}
Full source code: tutorials-android.blogspot.com (how to call android contacts list).
I do it this way for Android 2.2 Froyo release:
basically use eclipse to create a class like:
public class SomePickContactName extends Activity
then insert this code. Remember to add the private class variables and CONSTANTS referenced in my version of the code:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intentContact, PICK_CONTACT);
}//onCreate
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_CONTACT)
{
getContactInfo(intent);
// Your class variables now have the data, so do something with it.
}
}//onActivityResult
protected void getContactInfo(Intent intent)
{
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
while (cursor.moveToNext())
{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ( hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false" ;
if (Boolean.parseBoolean(hasPhone))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
// Find Email Addresses
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
Cursor address = getContentResolver().query(
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
null, null);
while (address.moveToNext())
{
// These are all private class variables, don't forget to create them.
poBox = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
street = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
city = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
state = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
postalCode = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
country = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
type = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
} //address.moveToNext()
} //while (cursor.moveToNext())
cursor.close();
}//getContactInfo
Looking around for an API Level 5 solution using ContactsContract API you could slightly modify the code above with the following:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
And then in onActivityResult use the column name:
ContactsContract.Contacts.DISPLAY_NAME
Here is the code snippet for get contact:
package com.contact;
import android.app.Activity;
import android.content.ContentResolver;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class GetContactDemoActivity extends Activity implements OnClickListener {
private Button btn = null;
private TextView txt = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
txt = (TextView) findViewById(R.id.textView1);
btn.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
if (arg0 == btn) {
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());
}
}
}
#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");
id = null;
name = null;
no = null;
phoneCur = null;
}
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());
}
}
}
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
String Number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_CONTACT && intent != null) //here check whether intent is null R not
{
}
}
because without selecting any contact it will give an exception. so better to check this condition.
The complete code is given below
package com.testingContect;
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.provider.Contacts.People;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class testingContect extends Activity implements OnClickListener{
/** Called when the activity is first created. */
EditText ed;
Button bt;
int PICK_CONTACT;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt=(Button)findViewById(R.id.button1);
ed =(EditText)findViewById(R.id.editText1);
ed.setOnClickListener(this);
bt.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.button1:
break;
case R.id.editText1:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
break;
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_CONTACT)
{
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
cursor.moveToNext();
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
Toast.makeText(this, "Contect LIST = "+name, Toast.LENGTH_LONG).show();
}
}//onActivityResult
}//class ends
Be careful while working with the android contact list.
Reading the contact list in the above methods works on most android devices except HTC One and Sony Xperia. It wasted my six weeks trying to figure out what is wrong!
Most tutorials available online are almost similar - first read "ALL" contacts, then show in Listview with ArrayAdapter. This is not memory efficient solution. Instead of looking for solutions on other websites first, have a look at developer.android.com. If any solution is not available on developer.android.com you should look somewhere else.
The solution is to use CursorAdapter instead of ArrayAdapter for retrieving the contact list. Using ArrayAdapter would work on most devices, but it's not efficient. The CursorAdapter retrieves only a portion of the contact list at run time while the ListView is being scrolled.
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
// Gets the ListView from the View list of the parent activity
mContactsList =
(ListView) getActivity().findViewById(R.layout.contact_list_view);
// Gets a CursorAdapter
mCursorAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.contact_list_item,
null,
FROM_COLUMNS, TO_IDS,
0);
// Sets the adapter for the ListView
mContactsList.setAdapter(mCursorAdapter);
}
Retrieving a List of Contacts: Retrieving a List of Contacts
To my surprise, you do not need users-permission CONTACT_READ to read the names and some basic information (Is the contact starred, what was the last calling time).
However, you do need permission to read the details of the contact like the phone number.
I am using this method to read Contacts
public static List<ContactItem> readPhoneContacts(Context context) {
List<ContactItem> contactItems = new ArrayList<ContactItem>();
try {
Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, "upper("+ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") ASC");
/*context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?",
new String[] { id },
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC");*/
Integer contactsCount = cursor.getCount(); // get how many contacts you have in your contacts list
if (contactsCount > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
ContactItem contactItem = new ContactItem();
contactItem.setContactName(contactName);
//the below cursor will give you details for multiple contacts
Cursor pCursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
// continue till this cursor reaches to all phone numbers which are associated with a contact in the contact list
while (pCursor.moveToNext()) {
int phoneType = pCursor.getInt(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
//String isStarred = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
String phoneNo = pCursor.getString(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//you will get all phone numbers according to it's type as below switch case.
//Logs.e will print the phone number along with the name in DDMS. you can use these details where ever you want.
switch (phoneType) {
case Phone.TYPE_MOBILE:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_MOBILE", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_HOME", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_WORK", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_WORK_MOBILE", " " + phoneNo);
break;
case Phone.TYPE_OTHER:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_OTHER", " " + phoneNo);
break;
default:
break;
}
}
contactItem.setSelectedAddress(getContactPostalAddress(pCursor));
pCursor.close();
contactItems.add(contactItem);
}
}
cursor.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return contactItems;
}//loadContacts
I have a code to save the contact in your database by shared preference
here is my code
public class MainActivity extends AppCompatActivity {
EditText nameInput,phoneInput;
TextView LargeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main22);
nameInput = (EditText) findViewById(R.id.nameInput);
phoneInput = (EditText) findViewById(R.id.phoneInput);
LargeText = (TextView) findViewById(R.id.textView2);
}
public void saveInfo (View view){
SharedPreferences sharedPref = getSharedPreferences("nameInfo" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor= sharedPref.edit();
editor.putString("name", nameInput.getText().toString());
editor.putString("phone", phoneInput.getText().toString());
editor.apply();
Toast.makeText(this, "Saved", Toast.LENGTH_LONG).show();
}
public void displayData(View view){
SharedPreferences sharedPref = getSharedPreferences("nameInfo" , Context.MODE_PRIVATE);
String name = sharedPref.getString("name", "");
String ph = sharedPref.getString ("phone","");
LargeText.setText(name + " " + ph);
}
}
-> Add a permission to read contacts data to your application manifest.
<uses-permission android:name="android.permission.READ_CONTACTS"/>
-> Use Intent.Action_Pick in your Activity like below
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
-> Then Override the onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForReslut
switch (requestCode) {
case RESULT_PICK_CONTACT:
Cursor cursor = null;
try {
String phoneNo = null ;
String name = null;
Uri uri = data.getData();
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
phoneNo = cursor.getString(phoneIndex);
textView2.setText(phoneNo);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
} else {
Log.e("MainActivity", "Failed to pick contact");
}
}
This will work check it out
I use the code provided by #Colin MacKenzie - III. Thanks a lot!
For someone who are looking for a replacement of 'deprecated' managedQuery:
1st, assuming using v4 support lib:
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
2nd:
your_(activity)_class implements LoaderManager.LoaderCallbacks<Cursor>
3rd,
// temporarily store the 'data.getData()' from onActivityResult
private Uri tmp_url;
4th, override callbacks:
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// create the loader here!
CursorLoader cursorLoader = new CursorLoader(this, tmp_url, null, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
getContactInfo(cursor); // here it is!
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
5th:
public void initLoader(Uri data){
// will be used in onCreateLoader callback
this.tmp_url = data;
// 'this' is an Activity instance, implementing those callbacks
this.getSupportLoaderManager().initLoader(0, null, this);
}
6th, the code above, except that I change the signature param from Intent to Cursor:
protected void getContactInfo(Cursor cursor)
{
// Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
while (cursor.moveToNext())
{
// same above ...
}
7th, call initLoader:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (PICK_CONTACT == requestCode) {
this.initLoader(data.getData(), this);
}
}
8th, don't forget this piece of code
Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
this.act.startActivityForResult(intentContact, PICK_CONTACT);
References:
Android Fundamentals: Properly Loading Data
Initializing a Loader in an Activity

Categories

Resources