Issue
I'm developing an app in which one of its features is to allow the user to input a phone number or select one from the phones contacts.
The activity has 3 EditTexts
along with 3 Buttons
each on the side, and the buttons open the Contacts Activity
and return the selected phone number and sets the EditText
accordingly.
I have tried setting separate cursors
for each button
.
I have also tried using different intent
variables.
My problem: When the user selects the contact to get data from, the cursor returns a different number. Either it returns the contact next to it or the contact previously selected.
The OnClick
method for the 3 buttons with startActivityForResult
.
//The intent
i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
public void onClick(View v) {
switch (v.getId()){
case (R.id.button1):
startActivityForResult(i, 0);
break;
//I know it's an ImageView
case (R.id.imageView1):
startActivityForResult(i, 1);
break;
case (R.id.imageView2):
startActivityForResult(i, 2);
break;
}
}
The OnActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode){
case (0) :
if (resultCode == Activity.RESULT_OK) {
Cursor c = getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
c.moveToFirst();
contact1 = c.getString(c.getColumnIndex(Phone.NUMBER));
et.setText(contact1);
}
break;
case (1) :
if (resultCode == Activity.RESULT_OK) {
Cursor c1 = getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
c1.moveToFirst();
contact2 = c1.getString(c1.getColumnIndex(Phone.NUMBER));
et2.setText(contact2);
}
break;
case (2) :
if (resultCode == Activity.RESULT_OK) {
Cursor c2 = getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
c2.moveToFirst();
contact3 = c2.getString(c2.getColumnIndex(Phone.NUMBER));
et3.setText(contact3);
}
break;
}
}
Solution
change Phone.CONTENT_URI
to intent.getData();
Uri contactData = intent.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
what you are doing wrong is querying each time the exact same query without regard to the intent
result...so of course you will get the same result each time
Also because you want to get the phone number add a projection
value:
String[] projection = {Phone.NUMBER};
getContentResolver().query(contactData, projection, null, null, null);
to better understand please read how to get contact phone number
Answered By - royB