I want to fetch contacts from my phonebook and save the name and number of a contact. I want to save 3 contacts. For which, 3 EditTexts And respective buttons are there. On button click user is directed to contacts where user can select desired contact. But, I am unable to implement Contact-fetch function for all 3 Edit Texts.
When i implement this with one contact only, code works fine. But, how can this be implemented in the case of multiple contacts.
Contact.java
package com.kamal.sos10;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;
import android.widget.Toast;
public class Contact extends AppCompatActivity {
EditText msg,editText2,editText3,editText4;
Button con1,con2,con3;
static final int PICK_CONTACT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
msg=(EditText)findViewById(R.id.msg);
editText2=(EditText)findViewById(R.id.editText2);
editText3=(EditText)findViewById(R.id.editText3);
editText4=(EditText)findViewById(R.id.editText4);
con1=(Button)findViewById(R.id.con1);
con2=(Button)findViewById(R.id.con2);
con3=(Button)findViewById(R.id.con3);
con1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text1", "1");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, PICK_CONTACT);
}
}
});
con2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text2", "2");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, PICK_CONTACT);
}
}
});
con3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text3", "3");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, PICK_CONTACT);
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String text1 = getIntent().getStringExtra("extra_text1");
Toast.makeText(Contact.this,text1,Toast.LENGTH_SHORT).show();
if (requestCode == PICK_CONTACT) {
if (resultCode == this.RESULT_OK) {
contactPicked(data);
}
}
}
private void contactPicked(Intent data) {
ContentResolver cr = this.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
cur.moveToFirst();
try {
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cur = this.getContentResolver().query(uri, null, null, null, null);
cur.moveToFirst();
// column index of the contact ID
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// column index of the contact name
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// column index of the phone number
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll(" ", "");
/*String text1 = getIntent().getStringExtra("extra_text1");
Toast.makeText(Contact.this,text1,Toast.LENGTH_SHORT).show();
if (text1.equals("1")) {
editText2.setText(phone);
}
String text2 = getIntent().getStringExtra("extra_text2");
if (text2 == "2") {
editText3.setText(phone);
}
String text3 = getIntent().getStringExtra("extra_text3");
if (text3 == "3") {
editText4.setText(phone);
*/}
pCur.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
You have used PICK_CONTACT = 1 for all three occurrences of startActivityForResult
startActivityForResult(intent, PICK_CONTACT);
Give different value for each occurrence of startActivityForResult like below:
con1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text", "1");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, 1);
}
}
});
con2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text", "2");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, 2);
}
}
});
con3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.putExtra("extra_text", "3");
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(Contact.this.getPackageManager()) != null) {
startActivityForResult(intent, 3);
}
}
});
Now in your onActivityResult change the below code:
if (requestCode == PICK_CONTACT) {
if (resultCode == this.RESULT_OK) {
contactPicked(data);
}
}
to this:
if (requestCode == 1 || requestCode == 2 || requestCode == 3) {
if (resultCode == this.RESULT_OK) {
contactPicked(data);
}
}
Now to print phone number in edittext box add the below code to contactPicked(Intent data):
String text = data.getStringExtra("extra_text").toString();
if (text.equals("1")) {
editText2.setText(phone);
}
else if (text == "2") {
editText3.setText(phone);
}
else (text == "3") {
editText4.setText(phone);
}
Related
Here is the code:
button.setOnClickListener(new View.OnClickListener() {
#Override public void onClick (View view){
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
}); return view;}
public void but(View v) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
} else {
Log.e("MainActivity", "Failed to pick contact");
}
}
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null;
String name = null;
Uri uri = data.getData();
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
if (phoneNo.startsWith("+")) {
if (phoneNo.length() == 13) {
String str_getMOBILE = phoneNo.substring(4);
editText.setText(("0") + str_getMOBILE);
}
if (phoneNo.length() == 16) {
String str_getMOBILE = phoneNo.substring(4);
editText.setText(("0") + str_getMOBILE);
}
} else {
editText.setText(phoneNo);
}
} catch (Exception e) {
e.printStackTrace();
}
}
You may be facing any of the following scenarios that led to the crash :
Your button is not declared and initiated properly in the onCreate() method of your main class. So please check if you have the below code in your onCreate() method :
Button button = (Button) findViewById(R.id.button);
Your app reads contacts from the user device I believe. In that case, please check if you have necessary permission to read contacts. For that, just check if the below line is included in the AndroidManifest.xml file :
<uses-permission android:name="android.permission.READ_CONTACTS" />
Check if you have permission to call the appropriate intent.
Your logcat trace will contain the exact line of code that led to the crash and the error code. So if you paste the logcat info here, you can get help.
Good day!
i am quite new in programming and i am trying to make a simple android app. i have here 2 edittext and 2 buttons inside my activity and what i want them to do is get the number of prefered contacts to text and the 1st edittext and 1st button succeeded but my problem is the button 2 also put the number on the 1st edittext that is supposed to put in 2nd edittext any idea?
this is my code..
public class SA extends Activity {
EditText con1;
EditText con2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_s);
con1 = (EditText) findViewById(R.id.cnum1);
con2 = (EditText) findViewById(R.id.cnum2);
((Button)findViewById(R.id.btnSelectContact1)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
((Button)findViewById(R.id.btnSelectContact2)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v2) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent2.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent2, 1);
}
});
}
#Override
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,},
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
showSelectedNumber(number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
protected void onActivityResult2(int requestCode2, int resultCode2, Intent data2) {
if (data2 != null) {
Uri uri2 = data2.getData();
if (uri2 != null) {
Cursor c2 = null;
try {
c2 = getContentResolver().query(uri2, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,},
null, null, null);
if (c2 != null && c2.moveToNext()) {
String number2 = c2.getString(0);
showSelectedNumber(number2);
}
} finally {
if (c2 != null) {
c2.close();
}
}
}
}
}
public void showSelectedNumber(String number) {
con1.setText(number);
}
public void showSelectedNumber2(String number2) {
con2.setText(number2);
}
No need of onActivityResult2() because startActivityForResult() gives you result back in onActivityResult() method.
So now your question would be, how you can manage different requests? Well, that you can do by passing different request code while calling startActivityForResult().
For example:
startActivityForResult(intent, 1); // first request
startActivityForResult(intent, 2); // second request
// you can pass any random number as a request code
Now you just need to perform the operations according to the request code received back in onActivityResult() method.
For example:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
if(requestCode == 1) {
...
...
} else if (requestCode == 2) {
...
...
}
}
}
gallery.class
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
public class gallery extends Fragment {
private static final int PICK_FROM_GALLERY = 1;
RelativeLayout gallerylayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.mainfragment, container, false);
gallerylayout = (RelativeLayout) v.findViewById(R.id.gallery_layout);
gallerylayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fireGallery();
}
});
return v;
}
private void fireGallery() {
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_FROM_GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_FROM_GALLERY:
String[] all_path = data.getStringArrayExtra("all_path");
System.out.println("all_path " + all_path); //Returns null
System.out.println("Data " + data.getExtras()); //Returns null
break;
}
}
}
The data in onActivityResult is always null, please correct me if anything wrong with my code. As mentioned both logs inside onActivityResult returns null. Note i am extending Fragment not activity.
Try this, you may get data from it:
#Override
protected void onActivityResult (int requestCode,int resultCode,Intent data){
super.onActivityResult (requestCode,resultCode,data);
try{
// When an Image is picked
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK
&& null != data){
// Get the Image from data
Uri selectedImage = data.getData ();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver ().query (selectedImage,
filePathColumn,null,null,null);
// Move to first row
cursor.moveToFirst ();
int columnIndex = cursor.getColumnIndex (filePathColumn[0]);
String imgDecodableString = cursor.getString (columnIndex);
cursor.close ();
Log.e ("Image Path",imgDecodableString);
Toast.makeText (this,"You have picked Image" ,
Toast.LENGTH_LONG).show ();
}
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 ();
Log.e ("Exception",e.toString ());
}
}
you can reading :http://inthecheesefactory.com/blog/how-to-fix-nested-fragment-onactivityresult-issue/en?fb_action_ids=780839882030502&fb_action_types=og.comments
Create ActivityResultEvent.java
import android.content.Intent;
/**
* Created by nuuneoi on 3/12/2015.
*/
public class ActivityResultEvent {
private int requestCode;
private int resultCode;
private Intent data;
public ActivityResultEvent(int requestCode, int resultCode, Intent data) {
this.requestCode = requestCode;
this.resultCode = resultCode;
this.data = data;
}
public int getRequestCode() {
return requestCode;
}
public void setRequestCode(int requestCode) {
this.requestCode = requestCode;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public Intent getData() {
return data;
}
public void setData(Intent data) {
this.data = data;
}
}
Create ActivityResultBus.java
import android.os.Handler;
import android.os.Looper;
import com.squareup.otto.Bus;
/**
* Created by nuuneoi on 3/12/2015.
*/
public class ActivityResultBus extends Bus {
private static ActivityResultBus instance;
public static ActivityResultBus getInstance() {
if (instance == null)
instance = new ActivityResultBus();
return instance;
}
private Handler mHandler = new Handler(Looper.getMainLooper());
public void postQueue(final Object obj) {
mHandler.post(new Runnable() {
#Override
public void run() {
ActivityResultBus.getInstance().post(obj);
}
});
}
}
// >>>>>>>>>>>>>> override onActivityResult on Activity
public class MainActivity extends ActionBarActivity {
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ActivityResultBus.getInstance().postQueue(
new ActivityResultEvent(requestCode, resultCode, data));
}
...
}
In fragment :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Don't forget to check requestCode before continuing your job
if (requestCode == 12345) {
// Do your job
tvResult.setText("Result Code = " + resultCode);
}
}
#Override
public void onStart() {
super.onStart();
ActivityResultBus.getInstance().register(mActivityResultSubscriber);
}
#Override
public void onStop() {
super.onStop();
ActivityResultBus.getInstance().unregister(mActivityResultSubscriber);
}
private Object mActivityResultSubscriber = new Object() {
#Subscribe
public void onActivityResultReceived(ActivityResultEvent event) {
int requestCode = event.getRequestCode();
int resultCode = event.getResultCode();
Intent data = event.getData();
onActivityResult(requestCode, resultCode, data);
}
};
if (requestCode == PICK_FROM_GALLERY && resultCode == Activity.RESULT_OK && null!=data)
{
Bitmap photo;
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
if (picturePath != null) {
Log.v("", picturePath);
cursor.close();
photo = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
photo = Bitmap.createScaledBitmap(photo, 1200, 1200, true);
this.data = baos.toByteArray();
chooseImage.setImageBitmap(photo);
}
else {
Utilities.showToast(getActivity(),
"This image is not on your device");
}
}
if You want to get picture from the gallery then you should use this function
The complete code of my Fragment:
public class ProfileEditPictureFragment extends BaseFragment implements OnClickListener {
private ImageView imageView = null;
private Button buttonPick = null;
private Button buttonSave = null;
private Button buttonCancel = null;
private File tempFile = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
this.sessionProfilePreferences = new SessionProfilePreferences(this.getActivity());
this.sessionLoginPreferences = new SessionLoginPreferences(this.getActivity());
this.sessionLoginSingleton = SessionLoginSingleton.getInstance(this.getActivity());
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
this.tempFile = new File(Environment.getExternalStorageDirectory(), "temp_photo.jpg");
}
else {
this.tempFile = new File(this.getActivity().getFilesDir(), "temp_photo.jpg");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile_picture_edit, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.imageView = (ImageView) view.findViewById(R.id.profile_picture_edit_imageview_photo);
this.buttonPick = (Button) view.findViewById(R.id.profile_picture_edit_button_pick);
this.buttonPick.setOnClickListener(this);
this.buttonSave = (Button) view.findViewById(R.id.profile_picture_edit_button_save);
this.buttonSave.setOnClickListener(this);
this.buttonCancel = (Button) view.findViewById(R.id.profile_picture_edit_button_cancel);
this.buttonCancel.setOnClickListener(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("ProfileEditPicture", "requestCode: " + requestCode);
Log.v("ProfileEditPicture", "resultCode: " + resultCode);
Log.v("ProfileEditPicture", "data: " + data);
Bitmap bitmap = null;
if(resultCode == Activity.RESULT_OK) {
if (requestCode == Globals.REQUEST_PICK_PHOTO) {
try {
InputStream inputStream = this.getActivity().getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(this.tempFile);
Helper.copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
this.startCropImage();
} catch (Exception e) {}
} else if (requestCode == Globals.REQUEST_CROP_PHOTO) {
String path = data.getStringExtra(CropActivity.IMAGE_PATH);
if (path == null) {
return;
}
bitmap = BitmapFactory.decodeFile(this.tempFile.getPath());
this.imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.profile_picture_edit_button_pick : {
this.pickPicture();
} break;
case R.id.profile_picture_edit_button_save : {
} break;
case R.id.profile_picture_edit_button_cancel : {
this.getActivity().finish();
}
}
}
private void pickPicture() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
this.startActivityForResult(Intent.createChooser(intent, "Select Picture"), Globals.REQUEST_PICK_PHOTO);
}
private void startCropImage() {
Intent intent = new Intent(this.getActivity(), CropActivity.class);
intent.putExtra(CropActivity.IMAGE_PATH, this.tempFile.getPath());
intent.putExtra(CropActivity.SCALE, true);
intent.putExtra(CropActivity.ASPECT_X, 3);
intent.putExtra(CropActivity.ASPECT_Y, 2);
this.startActivityForResult(intent, Globals.REQUEST_CROP_PHOTO);
}
}
But the resultCode is always 0 and the data is always null. Permissions are set ofcourse.
So how can i pick images from the gallery?
I test it on Nexus 4 with Android 5.0.1
Try ACTION_PICK like this
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
And on Activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
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]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} 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();
}
}
I was having same problem in one of my activities when I set launchMode="singleInstance" in manifest for that activity. It works fine when I remove that attribute. Although I don't know reason for this behaviour.
In my app I want to access contacts from the phone and fill the form with some data getting from the contact. When I am trying to run the Intent, I can see the list of contacts in my phone but it doesn't send any data back and onActivityResult is not being called. Can someone please help me as I am a beginner in android programming.
Here is part of my code :
On click event of a button called 'Contacts'
btn_contacts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
#SuppressWarnings("deprecation")
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
}
});
In onActivityResult in the same activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
Log.e("REcAddress","in activity result");
super.onActivityResult(requestCode, resultCode, data);
if(data!=null){
Log.e("REcAddress","hey");
}
if(requestCode == PICK_CONTACT && resultCode == RESULT_OK){
Uri contactData = data.getData();
Log.e("REcAddress",contactData.toString());
Cursor c = getContentResolver().query(contactData, null, null, null, null);
if(c.moveToFirst()){
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.e("REcAddress",name);
edt_rec_name.setText(name);
}
}
}
I have also attached an image to show the layout of the activity. I want to fill in as many details I can from contacts in the form. There is no error in Logcat too. Please, guide me.
Thanks.
first add permissions:
<uses-permission android:name="android.permission.READ_CONTACTS" />
then call intent on to pick contact on button click
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private static int PICK_CONTACT = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button pick = (Button) findViewById(R.id.butpick);
pick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pickContact();
}
});
}
private void pickContact() {
//you have used CONTENT_TYPE and here should be CONTENT_URI
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, 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.getCount() > 0) {
while (c.moveToNext()) {
String name=c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
edt_rec_name.setText(name);
}
}
}
}
You may not have the right permissions for accessing contacts on the phone. Are you using <uses-permission android:name="android.permission.READ_CONTACTS"/> in your Android Manifest?
Try the following code
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);