Retrieve contact name and phone after startActivityForResult() [duplicate] - java

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;
}
}

Related

Select multiple images from android gallery and get it path

I know that there is a lot of examples on the internet for it but no one of those does what I really want. I want to select multiple images with an intent and get it "url" like this code does with one. (I know that this code cannot select more than one, but I use this as example of what I'm trying to do)
Code:
public static final int RESULT_LOAD_IMG = 0;
public void LoadImg() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
ArrayList<Part> files = new ArrayList<>();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
files.add(new FilePart("uploadedfile[" + String.valueOf(files.size()) + "]", new File(picturePath)));
cursor.close();
}
}
Searching on the internet I found this example from Laith Mihyar in this post: Select multiple images from android gallery
and I want to do the same here, but the file path is different here and dont work for what I'm trying to do.
Code:
int PICK_IMAGE_MULTIPLE = 1
String imageEncoded;
List<String> imagesEncodedList;
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
String[] filePathColumn = { MediaStore.Images.Media.DATA };
imagesEncodedList = new ArrayList<String>();
if(data.getData()!=null){
Uri mImageUri=data.getData();
// Get the cursor
Cursor cursor = getContentResolver().query(mImageUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
cursor.close();
}else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
mArrayUri.add(uri);
// Get the cursor
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
imagesEncodedList.add(imageEncoded);
cursor.close();
}
Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
}
}
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
super.onActivityResult(requestCode, resultCode, data);
}
Thanks
There is no "file path". ACTION_GET_CONTENT does not have to return a file Uri, and most of the time on newer devices it will return a content Uri.
Use ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. Use DocumentFile and fromSingleUri() to get at metadata about the content identified by the Uri.
I can't even load it in an ImageView
Picasso and other image-loading libraries (even Ion) work with content Uri values without an issue.
I'm trying to upload those files with the Ion lib, that needs a path
The best solution would be to use a better HTTP client library, one that offers greater flexibility. OkHttp (with Okio) should be able to handle uploading from a Uri.
Or, use ContentResolver and openInputStream() to get an InputStream on the content. Use FileOutputStream to get a stream on some local file (e.g., in getCacheDir()). Use Java I/O to copy the bytes from the InputStream to the FileOutputStream. Then, use the local file with Ion.

Android - onActivityResult - Invalid column _data

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; :)

Selecting a contact from contact list crashing app

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);
}

The phone number is not right,using "ContactsContract"

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;
}
}
}

pick contacts with same name and more than two number

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));
}

Categories

Resources