I want to get the phone number form the local contact,but there's something wrong.For example,if I choose Person A,then the number showed is Person B's.
Here's the code.
//the button_click
public void testM(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
MainActivity.this.startActivityForResult(intent, 1);
}
//
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
final EditText phoneText = (EditText) findViewById(R.id.editText1);
switch (requestCode) {
case (1): {
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
c.moveToFirst();
String phoneNum = this.getContactPhone(c);
phoneText.setText(phoneNum);
}
break;
}
}
}
// get the number
private String getContactPhone(Cursor cursor) {
int phoneColumn = cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER);
int phoneNum = cursor.getInt(phoneColumn);
String phoneResult = "";
// System.out.print(phoneNum);
if (phoneNum > 0) {
// get the id
int idColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
String contactId = cursor.getString(idColumn);
// get cursor;
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
+ contactId, null, null);
// int phoneCount = phones.getCount();
// allPhoneNum = new ArrayList<String>(phoneCount);
if (phones.moveToFirst()) {
// traverse all the phone number
for (; !phones.isAfterLast(); phones.moveToNext()) {
int index = phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int typeindex = phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
int phone_type = phones.getInt(typeindex);
String phoneNumber = phones.getString(index);
switch (phone_type) {
case 2:
phoneResult = phoneNumber;
break;
}
// allPhoneNum.add(phoneNumber);
}
if (!phones.isClosed()) {
phones.close();
}
}
}
return phoneResult;
}
I know there's must something wrong with'ContactsContract.CommonDataKinds'.I'm not familiar with this Class.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final EditText phoneText = (EditText) findViewById(R.id.editText1);
switch (requestCode) {
case (1): {
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}, null, null, null);
if (c.moveToFirst())
{
int columnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
String phoneNum = c.getString(columnIndex);
phoneText.setText(phoneNum);
}
}
break;
}
}
}
Related
I am using code listed here Check Incoming number is stored in Contacts list or not android for checking whether incoming number exist or not in contacts. This code does not give correct result always.
Is there some correction required in this or some other better way to check?
Code:
String res = null;
try {
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String a = uri.getLastPathSegment();
Cursor c = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}, ContactsContract.CommonDataKinds.Phone._ID + "=?", new String[]{a}, null);
if (c != null) { // cursor not null means number is found contactsTable
if (c.getCount() > 0) {
if (c.moveToFirst()) { // so now find the contact Name
res = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//res = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
}
c.close();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return res;
Try the below code its simple & working for me.
public class TestActivity extends Activity {
private static final int REQUEST_CONTACT_NUMBER = 8512885487;
/** Pops the "select phone number" window */
public void onBrowseForNumbersButtonClicked(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, REQUEST_CONTACT_NUMBER);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(data != null && requestCode == REQUEST_CONTACT_NUMBER) {
Uri uriOfPhoneNumberRecord = data.getData();
String idOfPhoneRecord = uriOfPhoneNumberRecord.getLastPathSegment();
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI, new String[]{Phone.NUMBER}, Phone._ID + "=?", new String[]{idOfPhoneRecord}, null);
if(cursor != null) {
if(cursor.getCount() > 0) {
cursor.moveToFirst();
String formattedPhoneNumber = cursor.getString( cursor.getColumnIndex(Phone.NUMBER) );
Log.d("TestActivity", String.format("The selected phone number is: %s", formattedPhoneNumber));
}
cursor.close();
}
}
else {
Log.w("TestActivity", "WARNING: Corrupted request response");
}
}
else if (resultCode == RESULT_CANCELED) {
Log.i("TestActivity", "Popup canceled by user.");
}
else {
Log.w("TestActivity", "WARNING: Unknown resultCode");
}
}
}
I'm trying to do an application which is sending SMS, and MMS, so I need to retrieve the phone number and eventually an image.
My problem is, if I only the PICK_CONTACT case in onActivityResult, it's working fine, I got my contact phone number.
But if I'm adding the second part, PICK_IMAGE, when I'm clicking on my contact, I got a :
java.lang.IllegalArgumentException: Invalid column _data
But I can still taking images without any problems..
Both intent call
private static final int PICK_CONTACT = 3;
private static final int PICK_IMAGE = 4;
protected void onCreate(Bundle savedInstanceState) {
...
}
public void addImage() {
Intent choosePictureIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choosePictureIntent,PICK_IMAGE );
}
public void addContact(){
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
onActivityResult Code
public void onActivityResult(int reqCode, int resultCode, Intent data){
super.onActivityResult(reqCode, resultCode, data);
Uri contactData = data.getData();
switch(reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cur.moveToFirst()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
while (pCur.moveToNext()) {
phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
etPhoneNo.setText(phone);
}
pCur.close();
}
}
case (PICK_IMAGE) :
if (resultCode == Activity.RESULT_OK) {
try {
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
bmpFactoryOptions.inSampleSize = 2;
bmpFactoryOptions.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(contactData), null, bmpFactoryOptions);
imageView.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
Log.v("ERROR", e.toString());
}
ContentResolver cr = getContentResolver();
String [] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = cr.query(contactData, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
image_path = cursor.getString(column_index);
}
}
}
How can I resolve that?
I actually solved it ..
I just forgot break; :)
I'm trying to get a contact from my contact list in my application:
public void selecionar_contato(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(intent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Uri dados = data.getData();
Cursor c = getContentResolver().query(dados, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE }, null, null, null);
if(c.moveToFirst()){
String num = c.getString(0);
int type = c.getInt(1);
mostarToast(type,num);
}
break;
}
} else {
// gracefully handle failure
Log.w("Erro", "Warning: ac");
}
}
private void mostarToast(int type, String num) {
Toast.makeText(this, type + ": " + num, Toast.LENGTH_LONG).show();
}
But when i select the contact, my app crashes:
09-21 17:44:40.897: E/AndroidRuntime(17432): FATAL EXCEPTION: main
09-21 17:44:40.897: E/AndroidRuntime(17432): Process: com.example.pacixmobile, PID: 17432
09-21 17:44:40.897: E/AndroidRuntime(17432): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1001, result=-1, data=Intent { dat=content://com.android.contacts/contacts/lookup/298i107/602 flg=0x1 }} to activity {com.example.pacixmobile/com.example.pacixmobile.CadastroActivity}: java.lang.IllegalArgumentException: Invalid column data1
09-21 17:44:40.897: E/AndroidRuntime(17432): at android.app.ActivityThread.deliverResults(ActivityThread.java:3551)
I have to overwrite the onActivityResult method right? What am i missing?
The columns that you request are not directly available for the Uri you are using. You have picked a contact. You have not picked a phone number. A contact may have zero, one, or many phone numbers.
Given a Uri picked from ContactsContract.Contacts, you can retrieve columns available on ContactsContract.Contacts.
I have this in one activity and it's working fine, tested in phones and tablets.
I first get the selected contatct then her/his phone number. I need a mobile number if it's exists, also it's 9 digits (spanish number) removing the +34 or whatever country code it has.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
// super.onActivityResult(requestCode, resultCode, intent);
if (requestCode != 0x10 || resultCode != RESULT_OK)
{
super.onActivityResult(requestCode, resultCode, intent);
return;
}
Cursor cursor = null;
Uri contactUri = intent.getData();
long contactId = -1;
// get display name from the contact
try
{
cursor = getContentResolver().query(contactUri,
new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME }, null, null,
null);
if (cursor.moveToFirst())
{
String name = cursor.getString(1);
contactId = cursor.getLong(0);
etNombre.setText(name);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (cursor != null)
{
cursor.close();
cursor = null;
}
}
// do we have a valid contact ID?
if (contactId == -1) return;
// get all phone numbers with type from the contact
try
{
String tmpPhone = "";
boolean itsDone = false, gotPhone = false;
cursor = getContentResolver().query(Phone.CONTENT_URI, new String[] { Phone.TYPE, Phone.NUMBER },
Phone.CONTACT_ID + "=" + contactId, null, null);
// Pick up the first phone number
if (cursor.moveToFirst())
{
tmpPhone = cursor.getString(1);
itsDone = cursor.getInt(0) == Phone.TYPE_MOBILE;
gotPhone = true;
// if Not a mobile, search others numbers
if (!itsDone)
{
while (cursor.moveToNext())
{
if (cursor.getInt(0) == Phone.TYPE_MOBILE)
{
itsDone = true;
tmpPhone = cursor.getString(1);
break;
}
}
}
}
if (gotPhone)
{
int len = tmpPhone.length();
if (len > 9)
{
tmpPhone = parsePhone(tmpPhone);
len = tmpPhone.length();
if (len > 9)
tmpPhone = tmpPhone.substring(len - 9, len);
}
etTelefono.setText(tmpPhone);
etJornada.requestFocus();
}
else etTelefono.requestFocus();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
void cogerContactos()
{
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 0x10);
}
This question already has answers here:
Android contacts Display Name and Phone Number(s) in single database query?
(3 answers)
Closed 8 years ago.
I have started a new intent activity for result
Code:
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, 1);
And now I want to get the phone and number:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
Uri contactUri = data.getData();
String[] pN = {Phone.NUMBER};
String[] pNa = {Phone.CONTACT_ID};//idk
Cursor cP = getContentResolver().query(contactUri, pN, null, null, null);
cP.moveToFirst();
Cursor cPa = getContentResolver().query(contactUri, pNa, null, null, null);
cPa.moveToFirst();
int numc = cP.getColumnIndex(Phone.NUMBER);
String num = cP.getString(numc);
int namec = cPa.getColumnIndex(Phone.CONTACT_ID);//idk
String name = cPa.getString(namec);//idk
Log.i("", name);
}
if (resultCode == RESULT_CANCELED) {
//DO OTHER STUFF
}
}
}
The phone number is fine BUT I fail to retrieve the contact's GIVEN NAME!
Uri uri = data.getData();
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
cursor.moveToFirst();
number = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
Try this code , it might help with some minor changes...
static final int PICK_CONTACT_=1;
Intent intent_1 = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent_1, 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 cursor = managedQuery(contactData, null, null, null, null);
if (cursor.moveToFirst()) {
String id =cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
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 +" = "+ id,
null, null);
phones.moveToFirst();
cNumber = phones.getString(phones.getColumnIndex("data_1"));
System.out.println("number is:"+cNumber);
}
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
}
break;
}
}
I have tried to pick the contacts from phone by using following method in my project.It working fine.....
But in some case i will not work...For Ex: In case of Same Name with More than one number like personal/Home..
In this stage it will pick only first number.so i am unable to pick contacts from me. kindly give solutions.....
Code here
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();
cNumber = phones.getString(phones.getColumnIndex("data1"));
System.out.println("number is:"+cNumber);
}
/*name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Textcontact.setText(name);*/
edt.setText(cNumber);
}
}
break;
}
}
Thanks...
instead of
phones.moveToFirst();
you can browse the cursor for more item
int colIndex = phones.getColumnIndex("data1");
while (phones.moveToNext()) {
System.out.println("Found a number : " + phones.getString(colIndex));
}