I'm creating a PreferencesActivity where I have 3 preference items. When I click on each of them, I load contacts to pick one. After selecting a contact, I save it's name and phone number and I show it in the preference item. This is the way I do it:
preferences.xml
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:title="#string/contact">
<Preference
android:key="Contact1"
android:title="Contact 1"/>
<Preference
android:key="Contact2"
android:title="Contact 2"/>
<Preference
android:key="Contact3"
android:title="Contact 3"/>
</PreferenceCategory>
</PreferenceScreen>
UserSettingsActivity.java extending PreferenceActivity
SharedPreferences mPreferences;
Preference contact1;
Preference contact2;
Preference contact3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
contact1 = findPreference("Contact1");
contact2 = findPreference("Contact2");
contact3 = findPreference("Contact3");
contact1.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT_1);
return false;
}
});
contact2.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT_2);
return false;
}
});
contact3.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT_3);
return false;
}
});
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
Uri contactData = data.getData();
switch(reqCode) {
case (PICK_CONTACT_1):
if (resultCode == RESULT_OK){
String contactID = null;
String contactNumber = null;
String contactName = null;
/*Get contact ID*/
Cursor cursorID = getContentResolver().query(contactData, new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
/*Get contact number using ID*/
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID}, null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
/*Get name*/
Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();
/*Show on preferences*/
contact1.setTitle(contactName);
contact1.setSummary(contactNumber);
}
case (PICK_CONTACT_2):
if (resultCode == RESULT_OK){
String contactID = null;
String contactNumber = null;
String contactName = null;
/*Get contact ID*/
Cursor cursorID = getContentResolver().query(contactData, new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
/*Get contact number using ID*/
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID}, null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
/*Get name*/
Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();
/*Show on preferences*/
contact2.setTitle(contactName);
contact2.setSummary(contactNumber);
}
case (PICK_CONTACT_3):
if (resultCode == RESULT_OK){
String contactID = null;
String contactNumber = null;
String contactName = null;
/*Get contact ID*/
Cursor cursorID = getContentResolver().query(contactData, new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
/*Get contact number using ID*/
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID}, null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
/*Get name*/
Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();
/*Show on preferences*/
contact3.setTitle(contactName);
contact3.setSummary(contactNumber);
}
}
}
The problem is that when I set a contact for Contact1, also Contact2 and Contact3 are getting the same contact. Is the first time I'm working with preferences so I don't know what could be the reason for this.
The problem isn't with the Preferences but rather, with the switch statement.
You need to break at the end of each statement. Without a break, statements after a matching case label will be executed sequentially, regardless of the expressions of subsequent case labels.
Just include a break statement to prevent the statements in your switch blocks from falling through:
switch(reqCode) {
case (PICK_CONTACT_1):
---------
---------
break;
case (PICK_CONTACT_2):
---------
---------
break;
case (PICK_CONTACT_3):
---------
---------
break;
}
Related
I'm trying to retrieve the phone number of a user after selecting him in a picker activity.
This is the code to start the Activity:
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, Constants.COMMUNICATION_CONFIG_RESULT);
This is the code to retrive user name, id and phone number, it's used in a onActivityResult:
Uri contactData = data.getData();
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(contactData, null, null, null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
String name = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
phones.moveToFirst();
String contactNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("phoneNUmber", "The phone number is "+ contactNumber);
}
}
I get always the user name and id, and the user has always the phone number, but the cursor phone is always empty, regardless of the user selected.
Why can't I get the phone numbers?
Found out the problem. It must be:
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
if then I query the phone number via
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
The problem was that I selected different fields for the query.
// try this way,hope this will help you...
Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(i, 1);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
String phoneNumber = getPhoneNumber(data.getData());
if (phoneNumber.trim().length() > 0) {
// use this phoneNumber
} else {
ting("Phone Number Not Founded ...");
}
}
}
private String getPhoneNumber(Uri contactInfo) {
String phoneNumbers = "";
Cursor cursor = getContentResolver().query(contactInfo, null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String hashPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ("1".equalsIgnoreCase(hashPhone)) {
Cursor contactCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (contactCursor.moveToNext()) {
int type = contactCursor.getInt(contactCursor.getColumnIndex(Phone.TYPE));
if (type == Phone.TYPE_MOBILE) {
int colIdx = contactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
phoneNumbers = phoneNumbers.concat(contactCursor.getString(colIdx));
break;
}
}
contactCursor.close();
}
}
cursor.close();
return phoneNumbers;
}
I have textview. Clicking on it opens up native contact list. Once the users selects a contact, i should display the number in my app. I could display the name but not able to display number. Please help.
Thanks in Advance.
This is my code but after selecting the contact my app crashes."Unfortunately 'app_name' has stopped"
public void dail(View v)
{
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
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.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
}
}
Try this in your onActivity result. It will work.
ContentResolver cr = getContentResolver();
cursor = cr.query(intent.getData(), null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
if (Integer
.parseInt(cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
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();
} else {
snipp.showAlertDialog(getApplicationContext(), "No Number",
"Cannot read number", false);
}
}
cursor.close();
Try out as below in your onActivityResult
ContentResolver cr = getContentResolver();
Uri contactData = data.getData();
Log.v("Contact", contactData.toString());
Cursor c = managedQuery(contactData,null,null,null,null);
if(c.moveToFirst()){
id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
Log.v("Contact", "ID: " + id.toString());
name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.v("Contact", "Name: " + name.toString());
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while(pCur.moveToNext()){
phone = pCur.getString(pCur .getColumnIndex(Phone.NUMBER));
Log.v("getting phone number", "Phone Number: " + phone);
}
}
}
Try this
Put this code in your textview OnclickListner
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
In Activity result put this code
#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 = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(People.NAME))+" : "+c.getInt(c.getColumnIndexOrThrow(People.NUMBER));
//
txtContacts1.setText(name);
}
}
break;
}
For dail that no put this code
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + c.getInt(c.getColumnIndexOrThrow(People.NUMBER)));
context.startActivity(intent);
My code is as below:
String[] columns = {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER};
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, columns, null, null, null);
int ColumeIndex_ID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
int ColumeIndex_DISPLAY_NAME = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int ColumeIndex_HAS_PHONE_NUMBER = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
while(cursor.moveToNext())
{
String id = cursor.getString(ColumeIndex_ID);
String name = cursor.getString(ColumeIndex_DISPLAY_NAME);
String has_phone = cursor.getString(ColumeIndex_HAS_PHONE_NUMBER);
if(!has_phone.endsWith("0"))
{
System.out.println(name);
GetPhoneNumber(id);
}
}
cursor.close();
public String GetPhoneNumber(String id)
{
String number = "";
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone._ID + " = " + id, null, null);
if(phones.getCount() > 0)
{
while(phones.moveToNext())
{
number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
System.out.println(number);
}
phones.close();
return number;
}
I get contacts' name success, but get phone number fail in GetPhoneNumber().
The phones.getCount() always equal 0.
How can I modify?
Android Contact API For 2.0
//
// Find contact based on name.
//
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"DISPLAY_NAME = '" + NAME + "'", null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//
// Get all phone numbers.
//
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
switch (type) {
case Phone.TYPE_HOME:
// do something with the Home number here...
break;
case Phone.TYPE_MOBILE:
// do something with the Mobile number here...
break;
case Phone.TYPE_WORK:
// do something with the Work number here...
break;
}
}
phones.close();
}
cursor.close();
For more information see this link
try 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));
Log.i("Names", name);
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 need permission like -
android:name="android.permission.READ_CONTACTS"/>
Then, Calling the Contact Picker
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
Then,
#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 = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(People.NAME));
// TODO Whatever you want to do with the selected contact name.
}
}
break;
}
}
Old question but I don't see the following answer here.
private static final String[] PROJECTION ={
ContactsContract.Contacts._ID,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
ContactsContract.Contacts.PHOTO_THUMBNAIL_URI,
ContactsContract.Contacts.LOOKUP_KEY,
};
new CursorLoader(
this,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
PROJECTION,
null,
null,//mSelectionArgs,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY
);
Use column index ContactsContract.CommonDataKinds.Phone.NUMBER to retreive the phone number from the cursor.
U can use contact picker.
Call contact picker on any button and use the below code :
|*| Add in : AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS"/>
|*| Add in : activity_name.java
void calContctPickerFnc()
{
Intent calContctPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
calContctPickerIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(calContctPickerIntent, 1);
}
#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));
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));
Log.i("Number", ContctMobVar);
}
}
}
}
break;
}
}
Your can add this code on your Activity class:
private final int PICK_CONTACT = 5;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
//Your code
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACT && resultCode == RESULT_OK) {
Uri contactData = data.getData();
Cursor phones = getContentResolver()
.query(contactData,
null,
null,
null,
null);
String name = "", phoneNumber = "";
while (phones.moveToNext()) {
name = phones.getString(phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneNumber = phones.getString(phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
}
I know you might think this subject has been treated several times but this is different!
My app is supposed to get contact information (name, number) from a picked contact but I only get the name and I can't get the number.
#Override
public void onClick(View v) {
// Opening Contacts Window as a Window
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
// calling OnActivityResult with intent And Some contact for Identifie
startActivityForResult(contactPickerIntent, PICK);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
int indexName = c.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = c.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER);
nom = c.getString(indexName);
numero = c.getString(indexNumber);
//Visual confirm
Toast.makeText(this, "Contact " + nom +" enregistré!",
Toast.LENGTH_LONG).show();
//Save in prefs:
SharedPreferences manager =
PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = manager.edit();
editor.putString("num", numero);
editor.putString("nom", nom);
editor.commit();
The name is correct but the number causes a force close.
But if I replace it with the following there is no longer a force close, but the number is still incorrect (0 or 1).
int indexNumber = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)+1;
What should I do?
private void getDetails(){
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor names = getContentResolver().query(uri, projection, null, null, null);
int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
names.moveToFirst();
do {
String name = names.getString(indexName);
Log.e("Name new:", name);
String number = names.getString(indexNumber);
Log.e("Number new:","::"+number);
} while (names.moveToNext());
}
The above retrun all the name and number from from your contact database..
if you even need email id you add these lines also:::
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor email = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (email.moveToNext()) {
//to get the contact names
// if the email addresses were stored in an array
String emailid = email.getString(email.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("Email id ::", emailid);
String emailType = email.getString(email.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
Log.e("Email Type ::", emailType);
}
email.close();
}
I'm trying to retrieve contact list with there name and phone numbers. I try following code:
// Get a cursor over every contact.
Cursor cursor = getContentResolver().query(People.CONTENT_URI,
null, null, null, null);
// Let the activity manage the cursor lifecycle.
startManagingCursor(cursor);
// Use the convenience properties to get the index of the columns
int nameIdx = cursor.getColumnIndexOrThrow(People.NAME);
int phoneIdx = cursor. getColumnIndexOrThrow(People.NUMBER);
String[] result = new String[cursor.getCount()];
if (cursor.moveToFirst())
do {
// Extract the name.
String name = cursor.getString(nameIdx);
// Extract the phone number.
String phone = cursor.getString(phoneIdx);
result[cursor.getPosition()] = name + "-" +" "+ phone;
} while(cursor.moveToNext());
This code should return an array with the all contacts name and its phone number but this only returns name of the contact and returns NULL in phone number,
Example Output:
John - null
In Android manifest:
<uses-permission android:name="android.permission.READ_CONTACTS" />
Then in the activity:
editText.setOnFocusChangeListener(new OnFocusChangeListener(){
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
editText.setText("");
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
}
});
And then you have to catch the result of the action pick contact:
#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 = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst())
{
String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1"))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
phones.moveToFirst();
String cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(getApplicationContext(), cNumber, Toast.LENGTH_SHORT).show();
String nameContact = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
editText.setText(nameContact+ " "+ cNumber);
}
}
}
}
}
Don't use deprecated API access like as follow
Cursor cursor = getContentResolver().
query( Contacts.CONTENT_URI,
new String[]{Contacts.DISPLAY_NAME}, null, null,null);
if(cursor!=null){
while(cursor.moveToNext()){
Cursor c = getContentResolver().query(Phone.CONTENT_URI, new String[]{Phone.NUMBER, Phone.TYPE},
" DISPLAY_NAME = '"+cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME))+"'", null, null);
while(c.moveToNext()){
switch(c.getInt(c.getColumnIndex(Phone.TYPE))){
case Phone.TYPE_MOBILE :
case Phone.TYPE_HOME :
case Phone.TYPE_WORK :
case Phone.TYPE_OTHER :
}
}
}
}
Look on the sample code for retrieve the contacts from android mobile,
Cursor cursor = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String contactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phones = context.getContentResolver().query(
Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones
.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
switch (type) {
case Phone.TYPE_HOME:
Log.i("TYPE_HOME", "" + number);
break;
case Phone.TYPE_MOBILE:
Log.i("TYPE_MOBILE", "" + number);
break;
case Phone.TYPE_WORK:
Log.i("TYPE_WORK", "" + number);
break;
case Phone.TYPE_FAX_WORK:
Log.i("TYPE_FAX_WORK", "" + number);
break;
case Phone.TYPE_FAX_HOME:
Log.i("TYPE_FAX_HOME", "" + number);
break;
case Phone.TYPE_OTHER:
Log.i("TYPE_OTHER", "" + number);
break;
}
}
phones.close();
cursor.close();
HellBoy is right, Phone.xxx is depricated. I did it that way with a lookup-uri:
Uri look = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, "23N9983726428fnwe");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(look);
Experiment with Contacts.xxx on the first line, you will find the right sollution.
Try the below code.
Cursor managedCursor = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER}, null, null, Phone.DISPLAY_NAME + " ASC");
package com.number.contatcs;
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 Main2Activity 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.activity_main2);
Button getContacts = (Button) findViewById(R.id.button1);
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();
} else {
}
}
EditText numberEditText = (EditText) findViewById(R.id.w);
numberEditText.setText(number);
// EditText lastNameEditText =
// (EditText)findViewById(R.id.last_name);
// lastNameEditText.setText(lastName);
}
}
}
}