No callback (onActivityResult) from startActivityForResult - android

I'm trying to include functionality in an app for taking photos. The camera activity comes up, I can take a photo and tap the checkmark for using the photo just taken, but the app never receives it because onActivityResult is never called.
Here is the code that activates the camera activity:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
REQUEST_IMAGE_CAPTURE is set to 1.
The onActivityResult method that is never called looks like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
...
}
The app has only one activity, the main activity.
I have tried different settings in the manifest, with no luck.

As noted here you have to add this in the manifest.
Once this is added:
<uses-feature android:name="android.hardware.camera"
android:required="true" />
After you took the photo and accept it, the callback is called

<uses-feature
android:name="android.hardware.camera"
android:required="false"/>
private Uri mCapturedImageURI;
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, System.currentTimeMillis() + "PRESCRIPTION");
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intentPicture, 1);
public String getCameraPathFromURI(Uri contentUri) {
try {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e) {
return "";
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
if (mCapturedImageURI != null) {
realImagePath = getCameraPathFromURI(mCapturedImageURI);
}
}
break;
}

Related

Handle the Camera in a Fragment

Excuse me for any grammatical errors.
I would like to use the camera in a different activity than mainActivity.
I found this simple tutorial on google Taking Photos Simply, that says I have to use this function:
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
But, this function works fine only into the MainActivity, in fact, if I put this code in a different activity I get this error:
Cannot resolve method 'getPackageManager()'.
Some ideas?
Thank you!
Try out the following code:
static final int REQUEST_IMAGE_CAPTURE = 1;
Context c;
private void dispatchTakePictureIntent() {
Fragment yourFragment = this;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
yourFragment.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
Override your parent Activity's onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
Then add this to your fragment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == Activity.RESULT_OK) {
//Do something with your captured image. EX:-
try {
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]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath))
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
Excuse me, I don't know why, when I try this application on my Nexus 5X, the photo lose the quality when it appears into the ImageView. Application image (Image View): i.imgur.com/VunFaHF.png?1 Camera Image: i.imgur.com/wjJ2a4w.jpg

pass value if using front camera with intent method

i want to check if photo is taken with front camera with intent method.
below is code for run the camera
public void runCamera(){
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent takePictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(takePictureIntent, RESULT_CAMERA);
}
then below is activity result to process the taken image.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
...
case RESULT_CAMERA:
if(resultCode == RESULT_OK && mCapturedImageURI!=null){
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(mCapturedImageURI, projection, null, null, null);
String filePath;
if (cursor != null) {
cursor.moveToFirst();
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
filePath = cursor.getString(column_index_data);
}
else
filePath = data.getData().getPath();
GeneralizeImage mGI = new GeneralizeImage(this,filePath);
//getOrientationImage();
uploadFileToServer(mGI.Convert());
cursor.close();
}
else{
Toast.makeText(this, "Try Again", Toast.LENGTH_LONG).show();
}
break;
i appreciate any help from you guys, thanks.
You can pass parameter in your intent to open front camera.
Try this
takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 1);

Force certain app to receive the intent (not chooser) [duplicate]

I'm looking for a way to open the Android gallery application from an intent.
I do not want to return a picture, but rather just open the gallery to allow the user to use it as if they selected it from the launcher (View pictures/folders).
I have tried to do the following:
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
However this is causing the application to close once I select a picture (I know this is because of the ACTION_GET_CONTENT), but I need to just open the gallery.
Any help would be great.
Thanks
This is what you need:
ACTION_VIEW
Change your code to:
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
I hope this will help you. This code works for me.
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
ResultCode is used for updating the selected image to Gallery View
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if (cursor == null || cursor.getCount() < 1) {
return; // no cursor or no record. DO YOUR ERROR HANDLING
}
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if(columnIndex < 0) // no column index
return; // DO YOUR ERROR HANDLING
String picturePath = cursor.getString(columnIndex);
cursor.close(); // close cursor
photo = decodeFilePath(picturePath.toString());
List<Bitmap> bitmap = new ArrayList<Bitmap>();
bitmap.add(photo);
ImageAdapter imageAdapter = new ImageAdapter(
AddIncidentScreen.this, bitmap);
imageAdapter.notifyDataSetChanged();
newTagImage.setAdapter(imageAdapter);
}
You can open gallery using following intent:
public static final int RESULT_GALLERY = 0;
Intent galleryIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent , RESULT_GALLERY );
If you want to get result URI or do anything else use this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case QuestionEntryView.RESULT_GALLERY :
if (null != data) {
imageUri = data.getData();
//Do whatever that you desire here. or leave this blank
}
break;
default:
break;
}
}
Tested on Android 4.0+
Following can be used in Activity or Fragment.
private File mCurrentPhoto;
Add permissions
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
Add Intents to open "image-selector" and "photo-capture"
//A system-based view to select photos.
private void dispatchPhotoSelectionIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
this.startActivityForResult(galleryIntent, REQUEST_IMAGE_SELECTOR);
}
//Open system camera application to capture a photo.
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(App.Instance.getPackageManager()) != null) {
try {
createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (mCurrentPhoto != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhoto));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
Add handling when getting photo.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_IMAGE_SELECTOR:
if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = App.Instance.getContentResolver().query(data.getData(), filePathColumn, null, null, null);
if (cursor == null || cursor.getCount() < 1) {
mCurrentPhoto = null;
break;
}
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if(columnIndex < 0) { // no column index
mCurrentPhoto = null;
break;
}
mCurrentPhoto = new File(cursor.getString(columnIndex));
cursor.close();
} else {
mCurrentPhoto = null;
}
break;
case REQUEST_IMAGE_CAPTURE:
if (resultCode != Activity.RESULT_OK) {
mCurrentPhoto = null;
}
break;
}
if (mCurrentPhoto != null) {
ImageView imageView = (ImageView) [parent].findViewById(R.id.loaded_iv);
Picasso.with(App.Instance).load(mCurrentPhoto).into(imageView);
}
super.onActivityResult(requestCode, resultCode, data);
}
As you don't want a result to return, try following simple code.
Intent i=new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivity(i);
if somebody still getting the error, even after adding the following code
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
then you might be opening the intent in another class (by calling) due to this the app will crash when you click the button.
SOLUTION FOR THE PROBLEM
Put intent in the class file which is connected to the button's layout file.
for example- activity_main.xml contains the button and it is connected to MainActivity.java file. but due to fragmentation, you are defining the intent in some other class(lets says Activity.java) then your app will crash unless you place the intent in MainActivity.java file. I was getting this error and it is resolved by this.

File path from Camera Intent

I'm trying to get the file path of pictures that I took with Camera Intent as a String, but the String filePath is always null. What am I doing wrong?
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.btnImageCapture:
Intent openCamera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(openCamera, OPEN_CAMERA);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode){
case OPEN_CAMERA:
if (resultCode == RESULT_OK && data != null) {
Uri captureImage = data.getData();
String filePath = captureImage.getPath();
break;
}
}
}
This is how I get the image that was taken with the camera.
I create the file before and when the image gets saved then it gets saved to my file..
File externalFile = new File("Whatever you want the path to be...");
Uri uriSavedImage=Uri.fromFile(externalFile);
Intent launchcameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
launchcameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(launchcameraIntent,CAMERA_PIC_REQUEST);
Then when the result is received.
protected void onActivityResult(int requestCode,int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
Bitmap photo = BitmapUtils.decodeFileForDisplay(new File("Whatever your file's path is");
}
}
}
try the following passing your captureImage Uri as parameter:
public String getRealPathFromURI(Uri contentUri) {
String[] projx = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, projx, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
EDIT:
that is a common bug that getData() returns null on some devices. You need to use a pre-inserted Uri to prevent that. Example:
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
preinsertedUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new ContentValues());
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
Getting the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CAMERA_PIC_REQUEST:
if (resultCode != 0 && data != null) {
Uri imageUri = preinsertedUri;
}
break;
}

Android - Showing Phonebook contacts and selecting one

How can I show the list of contacts in phonebook on a click of a button and then select one of the contacts from it and then retrieve its contact number?
I don’t want to make my custom list. Is there a way to use Android's built-in functionality?
TRY THIS-->
setContentView(R.layout.main);
contactNumber = (TextView)findViewById(R.id.contactnumber);
Button buttonPickContact = (Button)findViewById(R.id.pickcontact);
buttonPickContact.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RQS_PICK_CONTACT){
if(resultCode == RESULT_OK){
Uri contactData = data.getData();
Cursor cursor = managedQuery(contactData, null, null, null, null);
cursor.moveToFirst();
String number = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
//contactName.setText(name);
contactNumber.setText(number);
//contactEmail.setText(email);
}
}
}
}
EDIT XML ADDED;
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/pickcontact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pick Contact" />
<TextView
android:id="#+id/contactnumber"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
I was doing the same thing in my application, and this is how to start a new intent for showing the list
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
And this is how to process the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_CONTACT) {
if (resultCode == RESULT_OK) {
Uri contactData = data.getData();
String number = "";
Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
cursor.moveToFirst();
String hasPhone = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
if (hasPhone.equals("1")) {
Cursor phones = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + contactId, null, null);
while (phones.moveToNext()) {
number = phones.getString(phones.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("[-() ]", "");
}
phones.close();
// Do something with the number
}
else {
Toast.makeText(getApplicationContext(), "This contact has no phone number", Toast.LENGTH_LONG).show();
}
cursor.close();
}
}
}
}
PICK_CONTACT is a constant defined in the class.
Intent i=new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(i, PICK_REQUEST);
The Intent delivered to your onActivityResult() method will contain the Uri of the chosen contact -- you will get this by calling getData() on that Intent.
Here is a sample project that demonstrates this, with the logic being implemented in a retained fragment, so we hang onto the selected contact across configuration changes (e.g., user rotating the screen).
You can also use ACTION_GET_CONTENT for this, and I think that's the more modern pattern, though ACTION_PICK certainly works and is all I have sample code for at the time of this writing. If you are reading this in the future (hi, future!), it's possible that the linked-to sample has been updated to use ACTION_GET_CONTENT.
For Kotlin, the request code for fetching a contact
private val REQUEST_CONTACT = 201
Intent to launch the phone book
private fun fetchPhoneNo() {
val intent = Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI)
startActivityForResult(intent, REQUEST_CONTACT)
}
Get the phone number in onActivityResult
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CONTACT && data?.data != null) {
val contactUri = data.data;
val crContacts = contentResolver.query(contactUri, null, null, null, null);
crContacts.moveToFirst()
val id = crContacts.getString(crContacts.getColumnIndex(ContactsContract.Contacts._ID));
if (Integer.parseInt(crContacts.getString(crContacts.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
val crPhones =
contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
arrayOf(id),
null)
crPhones.moveToFirst()
var phoneNo = crPhones.getString(
crPhones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
crPhones.close()
}
crContacts.close()
}
}
Here is the working code which I tried in API Level 29+
Step 1: Add Permission in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />
Step 2: Code to open the contacts dialog on a button click
private static final int REQ_PICK_CONTACT = 3;
private static final int CONTACT_PERMISSION_CODE = 1;
// Onclick handler
public void openContacts(View view) {
if(checkContactPermission()) {
openContactsDialog();
} else {
requestContactPermission();
}
}
// If permission is granted, then open contact box
private void openContactsDialog() {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, REQ_PICK_CONTACT);
}
// Check if the user has the permission granted
private boolean checkContactPermission() {
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED;
return result;
}
// Invoke request permission dialog
private void requestContactPermission() {
String[] permission = {Manifest.permission.READ_CONTACTS};
ActivityCompat.requestPermissions(this, permission, CONTACT_PERMISSION_CODE);
}
// After the permission is granted, open the contact dialog
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == CONTACT_PERMISSION_CODE) {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openContactsDialog();
}
}
}
Step 3: Handle contact selection
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_PICK_CONTACT) {
if (resultCode == RESULT_OK) {
Cursor cursor1, cursor2;
Uri uri = data.getData();
cursor1 = getContentResolver().query(uri, null, null, null, null);
if(cursor1.moveToFirst()) {
String contactId = cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts._ID));
String contactName = cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String hasNumber = cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if("1".equals(hasNumber)) {
cursor2 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
while(cursor2.moveToNext()) {
String contactNumber = cursor2.getString(cursor2.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Use contactName and contactNumber for your purposes
}
cursor2.close();
}
}
cursor1.close();
//edtName.setText(contactName);
//edtNumber.setText(number);
}
}
}
Solution courtesy: Pick Contact | Android Studio | Java (no audio whatsoever and very little annotation)
In the Nexus 5X emulator that I tested this with:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
Or:
Uri uri = Uri.parse("content://contacts");
Intent intent = new Intent(Intent.ACTION_PICK, uri);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
did not work for all contacts. I don't know why. But this works:
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1);
Add the PICK_CONTACT field:
private final int PICK_CONTACT = 55;
In onCreate():
viewPhonebook.setOnClickListener(v -> {
try {
Uri uri = Uri.parse("content://contacts");
Intent intent = new Intent(Intent.ACTION_PICK, uri);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
}
catch (Exception e) {
e.printStackTrace();
}
});
In onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case PICK_CONTACT:
Uri contactData = data.getData();
Cursor cursor = managedQuery(contactData, null, null, null, null);
cursor.moveToFirst();
String number = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
edtName.setText(contactName);
edtNumber.setText(number);
break;
}
}
}

Categories

Resources