I am trying to retrieve contact names given the contact phone number. I made a function that should work in all API versions, by I can't make it work in 1.6 and I can't see the problem, maybe someone can spot it?
Note that, I've replaced the API constants for strings so I don't have deprecated warning problems.
public String getContactName(final String phoneNumber)
{
Uri uri;
String[] projection;
if (Build.VERSION.SDK_INT >= 5)
{
uri = Uri.parse("content://com.android.contacts/phone_lookup");
projection = new String[] { "display_name" };
}
else
{
uri = Uri.parse("content://contacts/phones/filter");
projection = new String[] { "name" };
}
uri = Uri.withAppendedPath(uri, Uri.encode(phoneNumber));
Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null);
String contactName = "";
if (cursor.moveToFirst())
{
contactName = cursor.getString(0);
}
cursor.close();
cursor = null;
return contactName;
}
This seems to work fine in the latest versions:
private String getContactName(Context context, String number) {
String name = null;
// define the columns I want the query to return
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID};
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
Log.v(TAG, "Started uploadcontactphoto: Contact Found # " + number);
Log.v(TAG, "Started uploadcontactphoto: Contact name = " + name);
} else {
Log.v(TAG, "Contact Not Found # " + number);
}
cursor.close();
}
return name;
}
Use reflections instead of comparing sdk version.
public String getContactName(final String phoneNumber)
{
Uri uri;
String[] projection;
mBaseUri = Contacts.Phones.CONTENT_FILTER_URL;
projection = new String[] { android.provider.Contacts.People.NAME };
try {
Class<?> c =Class.forName("android.provider.ContactsContract$PhoneLookup");
mBaseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(mBaseUri);
projection = new String[] { "display_name" };
}
catch (Exception e) {
}
uri = Uri.withAppendedPath(mBaseUri, Uri.encode(phoneNumber));
Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null);
String contactName = "";
if (cursor.moveToFirst())
{
contactName = cursor.getString(0);
}
cursor.close();
cursor = null;
return contactName;
}
public static String getContactName(Context context, String phoneNumber)
{
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null)
{
return null;
}
String contactName = null;
if(cursor.moveToFirst())
{
contactName = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
}
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
return contactName;
}
private String getContactNameFromNumber(String number) {
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor cursor = context.getContentResolver().query(uri, new String[]{PhoneLookup.DISPLAY_NAME},null,null,null);
if (cursor.moveToFirst())
{
name = cursor.getString(cursor.getColumnIndex(PhoneLookup.D
Related
My code is working fine on any device .. but not working on android pie
I am trying to get the real path and the file name from the onActivityResult in a Fragment
and I am using the FileNameUtils from the apachi library
and using this library
https://gist.github.com/tatocaster/32aad15f6e0c50311626
but its giving me null
and this is my code
private void pickFile() {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"), PICKFILE_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICKFILE_REQUEST_CODE) {
filePath = RealPathUtil.getRealPath(getContext(), data.getData());
fileName = FilenameUtils.getName(filePath);
Log.i("FileNameIs",filePath + "Hello " + fileName );
// if (fileName !=null)
// {
// mFileName
// .setText(fileName.isEmpty() ? getString(R.string.failed_please_try_again) : fileName);
//
// deleteOldPath();
//
// }
}
}
updated .. Fixed it by the next ..
first
to get the file name
i used this function
public void dumpImageMetaData(Uri uri) {
String TAG = "TagIs";
// The query, since it only applies to a single document, will only return
// one row. There's no need to filter, sort, or select fields, since we want
// all fields for one document.
Cursor cursor = getActivity().getContentResolver()
.query(uri, null, null, null, null, null);
try {
// moveToFirst() returns false if the cursor has 0 rows. Very handy for
// "if there's anything to look at, look at it" conditionals.
if (cursor != null && cursor.moveToFirst()) {
// Note it's called "Display Name". This is
// provider-specific, and might not necessarily be the file name.
String displayName = cursor.getString(
cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
fileName = displayName ==null ? "Failed" : displayName;
deleteOldPath();
}
} finally {
cursor.close();
}
}
then i used this methods from this post
Get Real Path For Uri Android
to get the file Path
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
Log.i("URI",uri+"");
String result = uri+"";
// DocumentProvider
// if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isKitKat && (result.contains("media.documents"))) {
String[] ary = result.split("/");
int length = ary.length;
String imgary = ary[length-1];
final String[] dat = imgary.split("%3A");
final String docId = dat[1];
final String type = dat[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
} else if ("audio".equals(type)) {
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
dat[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
look at this . android reference
I was trying to get songs from album in my app. I wrote code below with some help on internet but now I'm getting all items as 0. I dont know why I'm getting 0.
public void songs()
{
String name;
long genreId;
Uri uri;
Cursor genrecursor;
Cursor tempcursor;
String[] proj1 = { android.provider.MediaStore.Audio.Albums._ID,
android.provider.MediaStore.Audio.Albums.ALBUM};
String[] proj2 = {MediaStore.Audio.Media.DISPLAY_NAME,MediaStore.Audio.Media.ALBUM_ID
,MediaStore.Audio.Media.DATA};
genrecursor = managedQuery(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, proj1, null, null, null);
if (genrecursor.moveToFirst()) {
do {
name = String.valueOf(genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM));
Log.i("Tag-album name", genrecursor.getString(Integer.parseInt(name)));
name = String.valueOf(genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Albums._ID));
genreId = Long.parseLong(genrecursor.getString(Integer.parseInt(name)));
uri = MediaStore.Audio.Genres.Members.getContentUri("external", genreId);
tempcursor = managedQuery(uri, proj2, null, null, null);
Log.i("Tag-Number of songs for this album", tempcursor.getCount() + "");
if (tempcursor.moveToFirst()) {
do {
name = String.valueOf(tempcursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
String art = String.valueOf(tempcursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
String path = String.valueOf(tempcursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
Log.i("Tag-Song name", tempcursor.getString(Integer.parseInt(name)));
albumInfo s = new albumInfo(name,art,path);
albumSongList.add(s);
} while (tempcursor.moveToNext());
}
} while (genrecursor.moveToNext());
}
}
i did this.
Uri uri= MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
String[] columns = {
MediaStore.Audio.Albums.ALBUM};
Cursor cursor =getApplicationContext().getContentResolver().
query(uri, columns, null,
null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
Log.v("bbb",
cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Albums.ALBUM)));
v=cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Albums.ALBUM));
} while (cursor.moveToNext());
}
// I want to list down song in album Rolling Papers (Deluxe Version)
String[] column = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.DISPLAY_NAME,
};
Intent i=getIntent();
final String value=i.getStringExtra("sol");
String [] x=new String[]{value};
String where = MediaStore.Audio.Albums.ALBUM + "=?";
Log.e("syn",v);
String whereVal[] = {v};
String orderBy = android.provider.MediaStore.Audio.Media.TITLE;
cursor =getApplicationContext().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
column, where, x,null);
if (cursor != null && cursor.moveToFirst()) {
do {
Log.v("Vipul",
cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
String name=cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String art=cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
String path=cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
albumInfo s = new albumInfo(name,art,path); // EXCLUDED
albumSongList.add(s);
} while (cursor.moveToNext());
}
}
I want to make a WhatsApp call to a specific user. I tried this and it doesn't work:
Uri uri = Uri.parse("callto:" + phoneNUmber);
Intent i = new Intent(Intent.ACTION_CALL, uri);
i.setPackage("com.whatsapp");
startActivity(i);
I know how to create a WhatsApp message, the code is similar and it works:
Uri uri = Uri.parse("smsto:" + phoneNUmber);
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.setPackage("com.whatsapp");
startActivity(i);
Simple solution is, Query ContactContract.Data for the _id and MIME type.
ContentResolver resolver = context.getContentResolver();
cursor = resolver.query(
ContactsContract.Data.CONTENT_URI,
null, null, null,
ContactsContract.Contacts.DISPLAY_NAME);
//Now read data from cursor like
while (cursor.moveToNext()) {
long _id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data._ID));
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
String mimeType = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
Log.d("Data", _id+ " "+ displayName + " " + mimeType );
}
The output will be like the following
12561 Snow vnd.android.cursor.item/vnd.com.whatsapp.profile
12562 Snow vnd.android.cursor.item/vnd.com.whatsapp.voip.call
Now save in DB or somewhere else only those _Ids whose MIME type is vnd.android.cursor.item/vnd.com.whatsapp.voip.call
And then you initiate Whatsapp call with those contacts like this way
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
// the _ids you save goes here at the end of /data/12562
intent.setDataAndType(Uri.parse("content://com.android.contacts/data/_id"),
"vnd.android.cursor.item/vnd.com.whatsapp.voip.call");
intent.setPackage("com.whatsapp");
startActivity(intent);
To make WhatsApp video call use below mime-string:
String mimeString = "vnd.android.cursor.item/vnd.com.whatsapp.video.call";
To make WhatsApp voice call use below mime-string:
String mimeString = "vnd.android.cursor.item/vnd.com.whatsapp.voip.call";
Use Below Code:
String displayName = null;
String name="ABC" // here you can give static name.
Long _id;
ContentResolver resolver = getApplicationContext().getContentResolver();
cursor = resolver.query(ContactsContract.Data.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME);
while (cursor.moveToNext()) {
_id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data._ID));
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
String mimeType = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
if (displayName.equals(name)) {
if (mimeType.equals(mimeString)) {
String data = "content://com.android.contacts/data/" + _id;
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_VIEW);
sendIntent.setDataAndType(Uri.parse(data), mimeString);
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
}
}
}
this code is to check number has whatsapp or not and make whatsapp audio and video call
first check wether number have whatsapp or not ...if you dont know
if rowContactId (return type of hasWhatsapp) is not equal to '0' then this number has whatsapp.
.
public String hasWhatsapp( getContactIDFromNumber(795486179).toString(),MAinactivity.this )
{
String rowContactId = null;
boolean hasWhatsApp;
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.Data.CONTACT_ID + " = ? AND account_type IN (?)";
String[] selectionArgs = new String[]{contactID, "com.whatsapp"};
Cursor cursor = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (cursor != null) {
hasWhatsApp = cursor.moveToNext();
if (hasWhatsApp) {
rowContactId = cursor.getString(0);
}
cursor.close();
}
return rowContactId;
}
public static int getContactIDFromNumber( contactNumber,Context context)
{
contactNumber = Uri.encode(contactNumber);
int phoneContactID = new Random().nextInt();
Cursor contactLookupCursor = context.getContentResolver().query(Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,contactNumber),new String[] {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID}, null, null, null);
while(contactLookupCursor.moveToNext())
{
phoneContactID = contactLookupCursor.getInt(contactLookupCursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
contactLookupCursor.close();
return phoneContactID;
}
//your number is support for whatsapp then come to here to make whatsapp call
// this is for whatsapp call
wtsapp_call.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String mimeString = "vnd.android.cursor.item/vnd.com.whatsapp.voip.call";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
//here you have to pass whatsApp contact number as contact_number ..
String name= getContactName( contact_number, MainActivity.this);
int whatsappcall=getContactIdForWhatsAppCall(name,MainActivity.this);
if (whatsappcall!=0) {
intent.setDataAndType(Uri.parse("content://com.android.contacts/data/" +whatsappcall),
"vnd.android.cursor.item/vnd.com.whatsapp.voip.call");
intent.setPackage("com.whatsapp");
startActivityForResult(intent, WHATSAPP_NUMMBER);
}
}
});
//for whatsapp video call
wtsapp_video.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
//here you have to pass whatsApp contact number as number..
String name= getContactName( number, MainActivity.this);
int videocall=getContactIdForWhatsAppVideoCall(name,MainActivity.this);
if (videocall!=0)
{
intent.setDataAndType(Uri.parse("content://com.android.contacts/data/" +videocall),
"vnd.android.cursor.item/vnd.com.whatsapp.video.call");
intent.setPackage("com.whatsapp");
startActivity(intent);
}
}
});
public String getContactName(final String phoneNumber, Context context)
{
Uri uri=Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber));
String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};
String contactName="";
Cursor cursor=context.getContentResolver().query(uri,projection,null,null,null);
if (cursor != null) {
if(cursor.moveToFirst()) {
contactName=cursor.getString(0);
}
cursor.close();
}
return contactName;
}
public int getContactIdForWhatsAppCall(String name,Context context)
{
cursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.Data._ID},
ContactsContract.Data.DISPLAY_NAME + "=? and "+ContactsContract.Data.MIMETYPE+ "=?",
new String[] {name,"vnd.android.cursor.item/vnd.com.whatsapp.voip.call"},
ContactsContract.Contacts.DISPLAY_NAME);
if (cursor.getCount()>0)
{
cursor.moveToNext();
int phoneContactID= cursor.getInt(cursor.getColumnIndex(ContactsContract.Data._ID));
System.out.println("9999999999999999 name "+name+" id "+phoneContactID);
return phoneContactID;
}
else
{
System.out.println("8888888888888888888 ");
return 0;
}
}
public int getContactIdForWhatsAppVideoCall(String name,Context context)
{
Cursor cursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.Data._ID},
ContactsContract.Data.DISPLAY_NAME + "=? and "+ContactsContract.Data.MIMETYPE+ "=?",
new String[] {name,"vnd.android.cursor.item/vnd.com.whatsapp.video.call"},
ContactsContract.Contacts.DISPLAY_NAME);
if (cursor.getCount()>0)
{
cursor.moveToFirst();
int phoneContactID= cursor.getInt(cursor.getColumnIndex(ContactsContract.Data._ID));
return phoneContactID;
}
else
{
System.out.println("8888888888888888888 ");
return 0;
}
}
If we pass rawContactId, then we can use that to directly fetch the ID associated with the whatsapp call URI.
private void whatsAppCall(Context context, String rawContactId) {
try {
int id = whatsAppCallId(context, rawContactId);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
String uriString = "content://com.android.contacts/data/" + id;
intent.setDataAndType(Uri.parse(uriString), "vnd.android.cursor.item/vnd.com.whatsapp.voip.call");
intent.setPackage("com.whatsapp");
startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "whatsAppCall Exception: " + e);
}
}
private long whatsAppCallId(Context context, String rawContactId){
ContentResolver resolver = context.getContentResolver();
String selection = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.Data.RAW_CONTACT_ID + " = ? ";
String[] selectionArgs = new String[] { "vnd.android.cursor.item/vnd.com.whatsapp.voip.call", rawContactId };
Cursor cursor = resolver.query(
ContactsContract.Data.CONTENT_URI,
null, selection, selectionArgs,
ContactsContract.Contacts.DISPLAY_NAME);
long _id=0;
while (cursor.moveToNext()) {
_id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data._ID));
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
String mimeType = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
Log.d(TAG, "Data: " + _id+ " "+ displayName + " " + mimeType );
}
return _id;
}
Answer provided by #Adnan Khan works in Android 11, but I wanted to provide the Kotlin version of his answer:
val resolver: ContentResolver = requireContext().contentResolver
val cursor: Cursor? = resolver.query(
ContactsContract.Data.CONTENT_URI,
null, null, null,
ContactsContract.Contacts.DISPLAY_NAME)
while(cursor!!.moveToNext()) {
val _id: Long = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data._ID))
val displayName: String = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME))
val mimeType: String = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE))
Log.i("Intents", "$_id $displayName $mimeType")
Now, the intent in Kotlin goes like this:
_id is the value you get from the previous routing
val intent = Intent()
intent.action = Intent.ACTION_VIEW
intent.setDataAndType(Uri.parse("content://com.android.contacts/data/_id"),
"vnd.android.cursor.item/vnd.com.whatsapp.voip.call")
intent.setPackage("com.whatsapp")
startActivity(intent)
Last but not least add the following to the AndroidManifest.xml:
<uses-permission
android:name="android.permission.CALL_PHONE"
androd:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.READ_CONTACTS"
androd:maxSdkVersion="30" />
After this, you need to go to Settings -> Apps -> Select your app and mark the two permissions as allowed.
There should be a way that the app ask you the first time it is run, but that is another topic.
// first check wether number have whatsapp or not ...if you dont know
//if rowContactId (return type of hasWhatsapp) is not equal to '0' then this number has whatsapp..
public String hasWhatsapp( getContactIDFromNumber(795486179).toString(),MAinactivity.this )
{
String rowContactId = null;
boolean hasWhatsApp;
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.Data.CONTACT_ID + " = ? AND account_type IN (?)";
String[] selectionArgs = new String[]{contactID, "com.whatsapp"};
Cursor cursor = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
if (cursor != null) {
hasWhatsApp = cursor.moveToNext();
if (hasWhatsApp) {
rowContactId = cursor.getString(0);
}
cursor.close();
}
return rowContactId;
}
public static int getContactIDFromNumber( contactNumber,Context context)
{
contactNumber = Uri.encode(contactNumber);
int phoneContactID = new Random().nextInt();
Cursor contactLookupCursor = context.getContentResolver().query(Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,contactNumber),new String[] {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID}, null, null, null);
while(contactLookupCursor.moveToNext())
{
phoneContactID = contactLookupCursor.getInt(contactLookupCursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
contactLookupCursor.close();
return phoneContactID;
}
//your number is support for whatsapp then come to here to make whatsapp call
// this is for whatsapp call
wtsapp_call.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String mimeString = "vnd.android.cursor.item/vnd.com.whatsapp.voip.call";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
//here you have to pass whatsApp contact number as contact_number ..
String name= getContactName( contact_number, MainActivity.this);
int whatsappcall=getContactIdForWhatsAppCall(name,MainActivity.this);
if (whatsappcall!=0) {
intent.setDataAndType(Uri.parse("content://com.android.contacts/data/" +whatsappcall),
"vnd.android.cursor.item/vnd.com.whatsapp.voip.call");
intent.setPackage("com.whatsapp");
startActivityForResult(intent, WHATSAPP_NUMMBER);
}
}
});
//for whatsapp video call
wtsapp_video.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
//here you have to pass whatsApp contact number as number..
String name= getContactName( number, MainActivity.this);
int videocall=getContactIdForWhatsAppVideoCall(name,MainActivity.this);
if (videocall!=0)
{
intent.setDataAndType(Uri.parse("content://com.android.contacts/data/" +videocall),
"vnd.android.cursor.item/vnd.com.whatsapp.video.call");
intent.setPackage("com.whatsapp");
startActivity(intent);
}
}
});
public String getContactName(final String phoneNumber, Context context)
{
Uri uri=Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber));
String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};
String contactName="";
Cursor cursor=context.getContentResolver().query(uri,projection,null,null,null);
if (cursor != null) {
if(cursor.moveToFirst()) {
contactName=cursor.getString(0);
}
cursor.close();
}
return contactName;
}
public int getContactIdForWhatsAppCall(String name,Context context)
{
cursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.Data._ID},
ContactsContract.Data.DISPLAY_NAME + "=? and "+ContactsContract.Data.MIMETYPE+ "=?",
new String[] {name,"vnd.android.cursor.item/vnd.com.whatsapp.voip.call"},
ContactsContract.Contacts.DISPLAY_NAME);
if (cursor.getCount()>0)
{
cursor.moveToNext();
int phoneContactID= cursor.getInt(cursor.getColumnIndex(ContactsContract.Data._ID));
System.out.println("9999999999999999 name "+name+" id "+phoneContactID);
return phoneContactID;
}
else
{
System.out.println("8888888888888888888 ");
return 0;
}
}
public int getContactIdForWhatsAppVideoCall(String name,Context context)
{
Cursor cursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{ContactsContract.Data._ID},
ContactsContract.Data.DISPLAY_NAME + "=? and "+ContactsContract.Data.MIMETYPE+ "=?",
new String[] {name,"vnd.android.cursor.item/vnd.com.whatsapp.video.call"},
ContactsContract.Contacts.DISPLAY_NAME);
if (cursor.getCount()>0)
{
cursor.moveToFirst();
int phoneContactID= cursor.getInt(cursor.getColumnIndex(ContactsContract.Data._ID));
return phoneContactID;
}
else
{
System.out.println("8888888888888888888 ");
return 0;
}
}
iv_whatsapp_call.setOnClickListener {
// val dialIntent = Intent(Intent.ACTION_DIAL)
// dialIntent.data = Uri.parse("tel:" + et_whatsapp.text.toString())
// startActivity(dialIntent)
val mimeString = "vnd.android.cursor.item/vnd.com.whatsapp.voip.call"
val resolver: ContentResolver = applicationContext.contentResolver
val cursor: Cursor? = resolver.query(ContactsContract.Data.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME)
while(cursor!!.moveToNext()) {
var Col_Index = cursor!!.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)
val _id = cursor.getLong(Col_Index)
Col_Index = cursor!!.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
var number = cursor.getString(Col_Index)
Col_Index = cursor!!.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
val displayName = cursor.getString(Col_Index)
Col_Index = cursor!!.getColumnIndex(ContactsContract.CommonDataKinds.Phone.MIMETYPE)
val mimeType = cursor.getString(Col_Index)
// println("Data: " + _id.toString() + " ---" + displayName + "---" + number + "---" + mimeType )
var my_number = et_whatsapp.text.toString()
my_number = my_number.replace(" ","")
my_number = my_number.replace("+","")
if(number.isNullOrBlank() == false) {
// println("Number : " + number )
number = number.replace(" ", "")
number = number.replace("+", "")
// my_number.substring(1)
// println(">>" + my_number)
if (number.endsWith(my_number.substring(1) + "#s.whatsapp.net")){
if (mimeType.equals(mimeString)) {
val data = "content://com.android.contacts/data/$_id"
val sendIntent = Intent()
sendIntent.action = Intent.ACTION_VIEW
sendIntent.setDataAndType(Uri.parse(data), mimeString)
sendIntent.setPackage("com.whatsapp")
startActivity(sendIntent)
break;
}
}
}
}
}
I go through the addressbook and try to get all contacts' photos which are not null.
I'm using android API8, so i cannot query for image_uri.
given photo_id (API 5), how can i get the photo bitmap?
here is my query:
public final static String[] PROJECTION2 = new String[] {
ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.PHOTO_ID
};
public static void fillAddressBookData() {
String sHash = null;
String where = ContactsContract.Contacts.IN_VISIBLE_GROUP + "= ? ";
String[] selectionArgs = new String[] {"1"};
Cursor cursor =
AppService
.getAppContext()
.getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION2, where,
selectionArgs, null);
...
try this:
private void GetImageByPhoneNumber(String number)
{
Uri uri1 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
Cursor test = getContentResolver().query(uri1,
new String[] { "photo_uri" }, null, null,
null);
if (test.getCount() > 0) {
test.moveToFirst();
Uri photoUri = Uri.parse(test.getString(test
.getColumnIndexOrThrow("photo_uri"))));
Bitmap image = getPhoto(context , photoUri);
}
test.close();
}
and getPhoto:
public static Bitmap getPhoto(Context context , Uri uri){
Bitmap bm = null;
try {
bm = BitmapFactory.decodeStream(context.getContentResolver()
.openInputStream(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (bm == null) {
bm = BitmapFactory.decodeResource(context.getResources(),
R.drawable.default_user_avatar);
}
return bm;
}
Try the next code snippet, it should do the trick
public Uri getPhotoUri(long contactId) {
ContentResolver contentResolver = getContentResolver();
try {
Cursor cursor = contentResolver
.query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID
+ "="
+ contactId
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
+ "'", null, null);
if (cursor != null) {
if (!cursor.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, contactId);
return Uri.withAppendedPath(person,
ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
I am new to Android and Java and this week I've been doing a self-taught crash course. So far what I've learned has not been too complicated as I've already built a number of years of coding experience. So, background history out of the way, onto my question.
The below code is two functions I wrote to take an image ID from a database and parse the correct Uri which I can then use to upload the photo to a website. So could you kind folks look over my code and let me know if I'm doing a terrible job or if I am heading in the right direction or even if there is a better/native way to do what I need.
Also, note: the below code does work. I just don't know if it is the right way to do it.
Thanks!
// Usage Map idPath = ImageIdPathFetcher.getRealIdPathFromID(getApplicationContext(), Integer.valueOf(image_id));
public static Map getRealIdPathFromID(Context context, Integer id) {
Map<String,String> idPath = new HashMap<String, String>();
Uri external_images_uri = MediaStore.Images.Media.getContentUri("external");
Uri internal_images_uri = MediaStore.Images.Media.getContentUri("internal");
// initialize uri
Uri uri = external_images_uri;
String ext_img_uri = external_images_uri.toString()+"/"+id;
String int_img_uri = internal_images_uri.toString()+"/"+id;
if(check_uri(context, ext_img_uri))
{
uri = Uri.parse(ext_img_uri);
}else if(check_uri(context, int_img_uri))
{
uri = Uri.parse(int_img_uri);
}else {
idPath.put("id", "");
idPath.put("path", "");
return idPath;
}
String[] proj = { Media.DATA, Media._ID };
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(Media.DATA);
cursor.moveToFirst();
String filepath = cursor.getString(column_index);
idPath.put("id", id.toString());
idPath.put("path", filepath);
return idPath;
}
public static boolean check_uri(Context context, String uri)
{
try{
ContentResolver cr = context.getContentResolver();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cur = cr.query(Uri.parse(uri), projection, null, null, null);
if(cur != null)
{
cur.moveToFirst();
String filePath = cur.getString(0);
if(! new File(filePath).exists()){
return false;
}
} else {
return false;
}
} catch (Exception e)
{
return false;
}
return true;
}
This is what I use
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
}
} finally {
cursor.close();
}
}
cursor = context.getContentResolver().query(
MediaStore.Images.Media.INTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
return Uri.withAppendedPath(MediaStore.Images.Media.INTERNAL_CONTENT_URI, String.valueOf(id));
}
} finally {
cursor.close();
}
}
return null;
}
It is possible to query both internal and external MediaStore database also with MergeCursor:
String myIdImgStr = "123"; // the unique ID of the image in the MediaStore
ContentResolver contentResolver = this.getContext().getContentResolver();
String [] proj = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
MergeCursor cursor = new MergeCursor(new Cursor[] {
MediaStore.Images.Media.query(contentResolver,
Uri.parse(MediaStore.Images.Media.INTERNAL_CONTENT_URI + "/" + myIdImgStr),
proj),
MediaStore.Images.Media.query(contentResolver,
Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + myIdImgStr),
proj)
});
if(cursor.getCount() == 1) {
cursor.moveToFirst();
String filepath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}