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;
}
}
}
Related
I'm developing an app, and in that app I have one button, named 'choose sound'. When user will click this button, he/she should be asked to choose any audio file from the file manager/memory.
So, I know that for this, I'll have to use Intent.Action_GetData. I'm doing the same:
//code start
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,1);
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode == 1){
if(resultCode == RESULT_OK){
//the selected audio.
Uri uri = data.getData();
int SoundID=soundPool.Load(uri.toString(), 1);
//SoundPool is already constructed and is working perfectly for the resource files
PlaySound(SoundID);
//PlaySound method is already defined
}
}
super.onActivityResult(requestCode, resultCode, data);
}
//end of code
but it's not working
Now, in OnActivityResult, I'm not getting that how to load the proper URI of the file selected by user, because before Android 4.4, it returns the different URI and after Android 4.4 it returns the different URI on intent.GetData();. Now, what I have to do?
Also, I know that for playing the audio file, I'll have to use SoundPool, and I have the code for that too, in fact it's working fine for the resource/raw/audio files, but how to load/play files in SoundPool from this URI?
In your onActivityResult(), do the following changes:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null)
{
String realPath = null;
Uri uriFromPath = null;
realPath = getPathForAudio(YourActivity.this, data.getData());
uriFromPath = Uri.fromFile(new File(realPath)); // use this uriFromPath for further operations
}
}
Add this method in your Activity:
public static String getPathForAudio(Context context, Uri uri)
{
String result = null;
Cursor cursor = null;
try {
String[] proj = { MediaStore.Audio.Media.DATA };
cursor = context.getContentResolver().query(uri, proj, null, null, null);
if (cursor == null) {
result = uri.getPath();
} else {
cursor.moveToFirst();
int column_index = cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
result = cursor.getString(column_index);
cursor.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
Hope It will do your job. You can play audio using MediaPlayer class also
You can put below codes in your project when you want to select audio.
Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload,1);
And override onActivityResult in the same Activity, as below
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode == 1){
if(resultCode == RESULT_OK){
//the selected audio.
Uri uri = data.getData();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Try to get the path :
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
then load it :
s2 = soundPool.load(YOU_PATH, PRIORITY);
I am launching the intent for selecting documnets using following code.
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"), 1);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
In onActivity results when i am trying to get the file path it is giving some other number in the place of file name.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
File myFile = new File(uri.toString());
String path = myFile.getAbsolutePath();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
That path value i am getting like this.
"content://com.android.providers.downloads.documents/document/1433"
But i want real file name like doc1.pdf etc.. How to get it?
When you get a content:// uri, you'll need to query a content resolver and then grab the display name.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
String displayName = null;
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
First Check if the permission is granted for Application.. Below method is used to check run-time permission'
public void onClick(View v) {
//Checks if the permission is Enabled or not...
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSION);
} else {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, USER_IMG_REQUEST);
}
}
and below method is used to find the uri path name of the file
private String getRealPathFromUri(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
CursorLoader cursorLoader = new CursorLoader(thisActivity, uri, projection, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column);
cursor.close();
return result;
}
and the above method can be used as
if (requestCode == USER_IMG_REQUEST && resultCode == RESULT_OK && data != null) {
Uri path = data.getData();
try {
String imagePath = getRealPathFromUri(path);
File file = new File(imagePath);
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part imageFile = MultipartBody.Part.createFormData("userImage", file.getName(), reqFile);
You can try this,m I hope it will help u:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("inside", "onActivityResult");
if(requestCode == FILE_MANAGER_REQUEST_CODE)
{
// Check if the user actually selected an image:
if(resultCode == Activity.RESULT_OK)
{
// This gets the URI of the image the user selected:
Uri selectedFileURI = data.getData();
File file = new File(getRealPathFromURI(selectedFileURI));
// Create a new Intent to send to the next Activity:
}
}
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
Here is the complete solution:
Pass your context and URI object from onActivityResult to below function to get the correct path:
it gives the path as /storage/emulated/0/APMC Mahuva/Report20-11-2017.pdf (where I've selected this Report20-11-2017.pdf file)
String getFilePath(Context cntx, Uri uri) {
Cursor cursor = null;
try {
String[] arr = { MediaStore.Images.Media.DATA };
cursor = cntx.getContentResolver().query(uri, arr, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
i am starting contact app using intent and selecting the contact from the list each time i choose different contact but i am getting the same contact again and again and i also don't know which contact it is? I have no idea what is going on?
Here is my code
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
and in activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Cursor c = null;
try
{
if(requestCode == PICK_CONTACT)
{
Uri contactData = data.getData();
c = getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
if (c.moveToFirst())
{
reciever = c.getString(c.getColumnIndex(Phone.NUMBER));
reciever = Main.removeCharacters(reciever);
int size = reciever.length();
Log.v(TAG, "To send "+reciever);
reciever = reciever.substring(size - 6, size);
}
new UploadPic().execute("");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
if(c != null)
{
c.close();
Log.v(TAG, "Cursor Closed");
}
}
}
You are assigning the contact URI to contactData yet you do not use it. When you call query() pass in contactData for the first argument rather than Phone.CONTENT_URI.
how to pick images from gallery into an android application?
I need to browse images form my gallery and choose them for my app .how it can be done ?
You'll need to use an intent to the gallery (well, "a gallery").
You can find a code example here (I haven't done it but it looks like it will work):
http://www.androidsnippets.com/get-file-path-of-gallery-image
Use this Code:
fromGalleryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//takePhotoFromGallery = true;// edited
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select Picture"),10);
}
});
And then add this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10 && resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
tempBitmap = BitmapFactory.decodeFile(imagePath); // this is your image
}
}
In Kotlin you can do this.
In onCreate method
binding.updatephoto.setOnClickListener {
contract.launch("image/*")
}
After onCreate
private val contract = registerForActivityResult(ActivityResultContracts.GetContent()){
it?.let {
val imageUri = it
}
}
I have the contact and I would like the user to choose from his phones or emails. Is that already provided by some picker or shall I implement my own?
Try this
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
startActivityForResult(intent, CONTACT_PICKER_RESULT);
}
});
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (CONTACT_PICKER_RESULT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(People.NAME));
editTextRecipient.setText(name);
}
}
break;
}
}