Setting a contact photo from URL - java

Im using this code to set a picture from a contact's phonenumber.
From the phonenumber i get a contact ID, and from the ID i can get a photo URL.
Im trying to set a picture in the imageview with: mPhotoView.setImageURI(uri);
But it wont work. I've debugged and the URL does NOT equal null.
The URL contains the following: content://com.android.contacts/contacts/502/photo
Does anyone know how to fix this?
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView mPhotoView = (ImageView) findViewById(R.id.imageView1);
Uri uri = getPhotoUri(Long.parseLong(fetchContactIdFromPhoneNumber(YOUR_PHONENUMBER))); //Set a number for yourself!
if (uri != null) {
mPhotoView.setImageURI(uri);
} else {
mPhotoView.setImageResource(R.drawable.ic_launcher);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public String fetchContactIdFromPhoneNumber(String phoneNumber) {
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cursor = this.getContentResolver().query(uri,
new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
null, null, null);
String contactId = "";
if (cursor.moveToFirst()) {
do {
contactId = cursor.getString(cursor
.getColumnIndex(PhoneLookup._ID));
} while (cursor.moveToNext());
}
return contactId;
}
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);
}
}

Related

Find all mp3 files in storage in android

Im trying to find all mp3 files but a have no idea and I found this code, the only problem is the getActivity() wasn't declared, I don't how know to fix, please help me. If has the better way of to do this, I accept sugestion.
here is my class:
public class SongsManager {
private ArrayList<Song> songsList;
public void getMp3Songs() {
Uri allSongsUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor = getActivity().getContentResolver().query(allSongsUri, null, null, null, selection);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Song song = new Song(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
songsList.add(song);
// album_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
// int album_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
// int artist_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
} while (cursor.moveToNext());
}
cursor.close();
}
}
}
Set parameter for Method (getMp3Songs) as Context:
public class SongsManager {
private ArrayList<Song> songsList;
public void getMp3Songs(Context ctx) {
Uri allSongsUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor = ctx.getContentResolver().query(allSongsUri, null, null, null, selection);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Song song = new Song(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
songsList.add(song);
// album_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
// int album_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
// int artist_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
} while (cursor.moveToNext());
}
cursor.close();
}
}
}
create Constructor and put there Context. And then call context instead of getActivity();
public class SongsManager {
private Context context;
public SongsManager(Context context){
this.context = context;
}
}

How to get the URI of profile pic from a contact number?

I have create custom incoming call screen that can current show the name and phone number of an incoming call. If the contact has a profile pic set that image should display in the ImageView. I calls the below method, and assigns the picture to the ImageView. The problem is that the else statement is always executed:
public static Uri getPhotoUri(String savedNumber, Context context) {
try {
Cursor cur = context
.getContentResolver()
.query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID
+ "="
+ getContactIDFromNumber(savedNumber,
context)
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
+ "'", null, null);
if (cur != null) {
if (!cur.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,
getContactIDFromNumber(savedNumber, context));
return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
public static int getContactIDFromNumber(String contactNumber,Context context) {
int phoneContactID = 0;
Cursor contactLookupCursor = context.getContentResolver().query(
Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(contactNumber)),
new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID},
null, null, null);
try {
contactLookupCursor.moveToFirst();
while (contactLookupCursor.moveToNext()) {
phoneContactID = contactLookupCursor.getInt(contactLookupCursor
.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
} finally {
contactLookupCursor.close();
}
return phoneContactID;
}
IncomingActivity:
#Override
protected void onResume() {
super.onResume();
callerNumber.setText(savedNumber);
callerName.setText(CommonMethods.getCallerName(savedNumber, this));
callerImageUri = CommonMethods.getPhotoUri(savedNumber, this);
if (callerImageUri != null) {
callerImage.setImageURI(callerImageUri);
} else {
callerImage.setImageResource(R.drawable.contact_default);
}
}
Does anyone have any ideas as to why "callerInamgeUri" is remaining null?

How to set an image for each row in list in onBindViewHolder?

I have a list of invitees. I am using a recyclerview and custom adapter. In this I am getting the photo from contacts by a contactId fetched with contact number.
Now I as set the imageUri to the image view. Only one image is shown to all the rows for which the imageUri is not null. And the position changes as I scroll up and down. Sometimes it shows the image and sometimes it dose not.
I want set the uri as per the position of invitee. How to do this?
Adapter :
public class InviteeAdapter extends RecyclerView.Adapter<InviteeAdapter.MyViewHolder>{
private List<Invitee> inviteeList;
int status;
Context context;
Cursor mCursor;
private ArrayList<Uri> imageArray;
public String contactId;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public com.github.siyamed.shapeimageview.CircularImageView profileImage;
String mobileNo;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.scheduleName);
profileImage = (com.github.siyamed.shapeimageview.CircularImageView) view.findViewById(R.id.eventsIcon);
imageArray = new ArrayList<>();
}
public String fetchContactIdFromPhoneNumber(String phoneNumber) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cursor = context.getContentResolver().query(uri,
new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID},
null, null, null);
String contactId = "";
if (cursor.moveToFirst()) {
do {
contactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.PhoneLookup._ID));
} while (cursor.moveToNext());
}
return contactId;
}
}
public InviteeAdapter(List<Invitee> inviteeList,Context context) {
this.inviteeList = inviteeList;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.invitee_card, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Uri imageUri;
Invitee invitee = new Invitee();
invitee = inviteeList.get(position);
holder.name.setText(invitee.getFName()+" "+ invitee.getLName());
contactId = holder.fetchContactIdFromPhoneNumber(invitee.getMobile());
ArrayList<String> contactArray = new ArrayList<>();
imageUri = getPhotoUri();
imageArray.add(getPhotoUri());
contactArray.add(contactId);
for(Uri id : imageArray)
{
// imageUri = getPhotoUri();
if(imageUri!= null) {
holder.profileImage.setImageURI(id);
}
else {
holder.profileImage.setBackgroundResource(R.drawable.ic_person_black_48dp);
}
}
/* status = invitee.;
if(status == 0)
{
holder.name.setTextColor(context.getResources().getColor(R.color.colorAccent));
}
else {
holder.name.setTextColor(context.getResources().getColor(R.color.grey));
}*/
}
public Uri getPhotoUri() {
try {
Cursor cur = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID + "=" + contactId + " AND "
+ ContactsContract.Data.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
null);
if (cur != null) {
if (!cur.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, Long
.parseLong(contactId));
return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
#Override
public int getItemCount() {
return inviteeList.size();
}
}
Can someone help please. Thank you..
Check this link it will help:
https://www.simplifiedcoding.net/android-custom-listview-with-images-using-recyclerview-and-volley/

how to get photo_uri from photo_id

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

Get contact name given a phone number in Android

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

Categories

Resources