Get selected contact image - Android - android

I'm trying to get the contacts image, but seems that I cannot get this to work. I've read other questions but none of them was able to resolve my issue.
Here is what I do, I retrieve the selected contact by doing:
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
and retreiving data:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode != 0) {
Log.d(TAG, resultCode + " result");
uriContact = intent.getData();
Log.d(TAG, resultCode + " result - " + intent.getData());
// handle the picked phone number in here.
String number = GetPhoneNumber();
getContactPhoto();
String name = getContactName();
if (contacts.size() > 0) {
for (Contact contact : contacts) {
if (contact.getContactID().equals(contactID))
return;
}
}
contacts.add(new Contact(name, contactID, number));
adapter = new ContactAdapter(getActivity(), (ArrayList<Contact>) contacts);
((ListView) view.findViewById(R.id.emergency_contact_list)).setAdapter(adapter);
view.findViewById(R.id.emergency_contact_done).setEnabled(true);
}
}
}
here is how I try to display the contact's image:
private void getContactPhoto() {
Bitmap photo = null;
try {
//inputStream is always null - why so?
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getActivity().getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));
Log.d(TAG, "input stream " + inputStream);
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
ImageView imageView = (ImageView) view.findViewById(R.id.testimg);
imageView.setImageBitmap(photo);
assert inputStream != null;
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
As I noticed in the getContactPhoto method inputStream is always null, can anyone tell me how can I get contact photo in the propper way?
Thanks!

you can use this method for loading contact's photo as a byte[]
public static byte[] loadIcon(Context context, long contactId, boolean highRes) {
byte[] icon = null;
// Load the icon
if (contactId <= 0) {
return icon;
}
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
try {
InputStream is = null;
is = Contacts.openContactPhotoInputStream(context.getContentResolver(), contactUri, highRes);
if (is != null) {
int iconSize = is.available();
// this is if you want to avoid loading large pictures
if (iconSize > 200 * 1024) {
Log.d(TAG, "load contact. Icon too big: " + iconSize);
} else {
icon = new byte[iconSize];
is.read(icon, 0, icon.length);
}
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return icon;
}

Related

Pick image from Gallery - File not found when running newer Android versions

I am working on a address book like Android SDK 14+ app. The users should be able to pick an image from the Gallery to add it to a contact entry.
Running the following code to pick and copy the image is no problem in API 14-20 but does not work in API 21+. The file is not found anymore:
protected void pickFoto() {
if (filePermissionsRequired()) {
askForFilePermissions(new PermissionRequestCompletionHandler() {
#Override
public void onPermissionRequestResult(boolean permissionGranted) {
if (permissionGranted)
addOrEditReceipt();
}
});
return;
}
Intent pickPhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhotoIntent , PICK_FOTO_ACTION);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
...
case PICK_FOTO_ACTION: {
Uri imageUri = intent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
File imgFile = new File(filePath);
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
public interface PermissionRequestCompletionHandler {
void onPermissionRequestResult(boolean permissionGranted);
}
private PermissionRequestCompletionHandler permissionRequestCompletionHandler;
public boolean filePermissionsRequired() {
if (Build.VERSION.SDK_INT >= 23)
return checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED;
else
return false;
}
public boolean askForFilePermissions(PermissionRequestCompletionHandler completionHandler) {
if (Build.VERSION.SDK_INT >= 23) {
permissionRequestCompletionHandler = completionHandler;
boolean hasPermission = this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if (!hasPermission) {
this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return true;
}
}
permissionRequestCompletionHandler = null;
return false;
}
The app has runtime permissions to access the Gallery. So what am I doing wrong? How to access the file on newer API versions?
}
try below code to open the camera and getting result:
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + System.currentTimeMillis() + ".png");
Uri imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICK_FOTO_ACTION);
for getting result :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case PICK_FOTO_ACTION: {
Uri imageUri = imageUri;
File imgFile = new File(imageUri.getPath());
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
}
for getting actual path from uri :
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s=cursor.getString(column_index);
cursor.close();
return s;
}
remove unwanted uri part :
public String RemoveUnwantedString(String pathUri){
//pathUri = "content://com.google.android.apps.photos.contentprovider/-1/2/content://media/external/video/media/5213/ORIGINAL/NONE/2106970034"
String[] d1 = pathUri.split("content://");
for (String item1:d1) {
if (item1.contains("media/")) {
String[] d2 = item1.split("/ORIGINAL/");
for (String item2:d2) {
if (item2.contains("media/")) {
pathUri = "content://" + item2;
break;
}
}
break;
}
}
//pathUri = "content://media/external/video/media/5213"
return pathUri;
}
For versions 21 and higher you can do this , you need to add a condition to check the SDK version for this. Exectute this code in the API 21+ condition block.
String wholeID = DocumentsContract.getDocumentId(imageUri );
String id = wholeID.split(":")[1];
String sel = MediaStore.Images.Media._ID + "=?";
cursor =
getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[]{ id }, null);
try
{
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
}
catch(NullPointerException e) {
}
Call the Gallery with belo code
public static final int SELECT_IMAGE_FROM_GALLERY_CODE = 701;
public static void callGallery(Activity activity) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
activity.startActivityForResult(Intent.createChooser(intent, "Complete action using"),
SELECT_IMAGE_FROM_GALLERY_CODE);
}
In OnActivityResult, read URI and read path from uri.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CommonUtils.SELECT_IMAGE_FROM_GALLERY_CODE) {
if (data != null) {
Uri selectedImageUri = data.getData();
// get path from Uri
String imagepath = getPath(this, selectedImageUri);
if (null != imagepath && (!imagepath.isEmpty())) {
// if the image path is not null and not empty, copy image to sdcard
try {
copyDirectoryOrFile(new File(imagepath), new File(myTargetImageFilePath));
} catch (IOException e) {
e.printStackTrace();
}
// load the image into imageView with the help og glide.
loadImageWithGlide(myImageViewContactImage,
myTargetImageFilePath, myDefaultImagePath, myErrorImagePath, false);
} else {
Toast.makeText(this, "Error: Photo selection failed.", Toast.LENGTH_LONG).show();
}
}
}
}
public void loadImageWithGlide(ImageView theImageViewToLoadImage,
String theLoadImagePath, int theDefaultImagePath, int theErrorImagePath,
boolean theIsSkipMemoryCache) {
if (theIsSkipMemoryCache) {
Glide.with(ProfileActivity.this) //passing context
.load(theLoadImagePath) //passing your url to load image.
.placeholder(theDefaultImagePath) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url.
.error(theErrorImagePath)//in case of any glide exception or not able to download then this image will be appear . if you won't mention this error() then nothing to worry placeHolder image would be remain as it is.
.diskCacheStrategy(DiskCacheStrategy.ALL) //using to load into cache then second time it will load fast.
//.animate(R.anim.fade_in) // when image (url) will be loaded by glide then this face in animation help to replace url image in the place of placeHolder (default) image.
.centerCrop()
.into(theImageViewToLoadImage); //pass imageView reference to appear the image.
} else {
Glide.with(ProfileActivity.this)
.load(theLoadImagePath)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.centerCrop()
.into(theImageViewToLoadImage);
}
}
public static String getPath(Context theCtx, Uri uri) {
try {
Cursor cursor = (theCtx).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 = (theCtx).getContentResolver().query(
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;
} catch (Exception e) {
return null;
}
}
public static void copyDirectoryOrFile(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists() && !targetLocation.mkdirs()) {
throw new IOException("Cannot create directory " + targetLocation.getAbsolutePath());
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectoryOrFile(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
File directory = targetLocation.getParentFile();
if (directory != null && !directory.exists() && !directory.mkdirs()) {
throw new IOException("Cannot create directory " + directory.getAbsolutePath());
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
To load image with glide, add following dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'

how to select multiple images and convert them to base 64?

I am working in application in which I want user to select multiple and convert them to base64, so that I can sent it to server. Is it possibile to select multiple images from gallery and then convert them to base64 and then send it to server
Intent intent = new Intent();
intent.setType("*/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "android.intent.action.SEND_MULTIPLE"), SELECT_PICTURE);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == SELECT_PICTURE) {
if (resultCode == RESULT_OK) {
//data.getParcelableArrayExtra(name);
//If Single image selected then it will fetch from Gallery
filePath = data.getData();
filePath = data.getData();
if (null != filePath) {
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
// img.setImageBitmap(bitmap);
if (filePath.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(filePath, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
file_name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
// text.setText(file_name+",");
img_name.add(file_name);
img_pic.add(getStringImage(bitmap));
// Toast.makeText(this, "1." + file_name, Toast.LENGTH_SHORT).show();
}
} finally {
cursor.close();
}
} else {
String path = data.getData().getPath();
file_name = path.substring(path.lastIndexOf("/") + 1);
// text.setText(file_name);
img_name.add(file_name);
img_pic.add(getStringImage(bitmap));
//Toast.makeText(this, "2." + file_name, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
Sure you can either manage selecting and displaying the images yourself or you can rely on Androids File Intent chooser to let them select and return. You can then use the URIs provided to retrieve the images, convert and send.
Getting user selected images is simple so I won't post that, but just in case it is something you are not familiar with, here is a link that will walk you through it. Select multiple images from android gallery
Now converting to Base64 should be asynctask
Use the following:
public class Base64EncodeMediaAsyncTask extends AsyncTask<Void, Void, MediaModel> {
/*///////////////////////////////////////////////////////////////
// MEMBERS
*////////////////////////////////////////////////////////////////
private static final String TAG = Globals.SEARCH_STRING + Base64EncodeMediaAsyncTask.class.getSimpleName();
private MediaModel mMediaModelToConvert;
/*///////////////////////////////////////////////////////////////
// CONSTRUCTOR
*////////////////////////////////////////////////////////////////
public Base64EncodeMediaAsyncTask(MediaModel model){
mContext = context;
mMediaModelToConvert = model; //it's just a file wrapper, nothing special lol.
}
/*///////////////////////////////////////////////////////////////
// OVERRIDES
*////////////////////////////////////////////////////////////////
#Override
protected MediaModel doInBackground(Void... params) {
try{
InputStream inputStream = new FileInputStream(mMediaModelToConvert.getAbsoluteLocalPath());//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffer = new byte[(int) new File(mMediaModelToConvert.getAbsoluteLocalPath()).length()];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
bytes = output.toByteArray();
mMediaModelToConvert.setBase64String(Base64.encodeToString(bytes, Base64.DEFAULT));
}catch (Exception ex){
A35Log.e(TAG, "Failed to get base 64 encoding for file: " + mMediaModelToConvert.getAbsoluteLocalPath());
return null;
}
return mMediaModelToConvert;
}
#Override
protected void onPostExecute(MediaModel success) {
super.onPostExecute(success);
}
}

how to show image in image view

I am working on android custom camera application when i click on gallery view it show mobile default gallery and show photos that i clicked but i want when i click on gallery then clicked image show in my custom view how can i implement
public void clickedGallery(View view) {
if (MyDebug.LOG)
Log.d(TAG, "clickedGallery");
//Intent intent = new Intent(Intent.ACTION_VIEW, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Uri uri = null;
Media media = getLatestMedia();
if (media != null) {
uri = media.uri;
}
if (uri != null) {
// check uri exists
if (MyDebug.LOG)
Log.d(TAG, "found most recent uri: " + uri);
try {
ContentResolver cr = getContentResolver();
ParcelFileDescriptor pfd = cr.openFileDescriptor(uri, "r");
if (pfd == null) {
if (MyDebug.LOG)
Log.d(TAG, "uri no longer exists (1): " + uri);
uri = null;
}
pfd.close();
} catch (IOException e) {
if (MyDebug.LOG)
Log.d(TAG, "uri no longer exists (2): " + uri);
uri = null;
}
}
if (uri == null) {
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
if (!is_test) {
// don't do if testing, as unclear how to exit activity to finish test (for testGallery())
if (MyDebug.LOG)
Log.d(TAG, "launch uri:" + uri);
final String REVIEW_ACTION = "com.android.camera.action.REVIEW";
try {
// REVIEW_ACTION means we can view video files without autoplaying
Intent intent = new Intent(REVIEW_ACTION, uri);
this.startActivity(intent);
} catch (ActivityNotFoundException e) {
if (MyDebug.LOG)
Log.d(TAG, "REVIEW_ACTION intent didn't work, try ACTION_VIEW");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
// from http://stackoverflow.com/questions/11073832/no-activity-found-to-handle-intent - needed to fix crash if no gallery app installed
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("blah")); // test
if (intent.resolveActivity(getPackageManager()) != null) {
this.startActivity(intent);
} else {
preview.showToast(null, R.string.no_gallery_app);
}
}
}
}
Here is the complete code you can modify the requestCode to whatever you would have declared in your code and you can either pass the Uri or the actual location of the file in the next activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_CANCELED) {
if (requestCode == SELECT_FILE && (data != null)) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null,
null);
assert cursor != null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
if(selectedImagePath == null) {
selectedImagePath = getActualPathFromUri(selectedImageUri);
}
cursor.close();
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
private String getActualPathFromUri(Uri selectedImageUri) {
Bitmap bitmap = null;
try {
bitmap = getBitmapFromUri(selectedImageUri);
} catch (IOException e) {
e.printStackTrace();
}
if(bitmap == null) {
return null;
}
File imageFileFolder = new File(getCacheDir(),"appName");
if( !imageFileFolder.exists() ){
imageFileFolder.mkdir();
}
FileOutputStream out = null;
File imageFileName = new File(imageFileFolder, "appName-" + System.currentTimeMillis() + ".jpg");
try {
out = new FileOutputStream(imageFileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
Log.i("Exception", e.getMessage());
} finally {
if(out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imageFileName.getAbsolutePath();
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
assert parcelFileDescriptor != null;
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
When you back from camera after you take picture or back from gallery your onActivityResult method will call. So override your onActivityResult like the following
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
//Read your image here and set in your imageView
}
}
Edit:
Set image to image view
Inside of the onActivityResult
if(data.getData()==null){
bitmap = (Bitmap)data.getExtras().get("data");
}else{
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
}
yourImageView.setImageBitmap(img);

Android: Saving image from gallery and then loading into imageview

I have an onclick that will allow a user to select a file from gallery like so:
case R.id.ColourCustom:
customBorderChange();
break;
private void customBorderChange() {
final ImageView QPBackground = (ImageView) findViewById(R.id.QPBackground);
menuHandler.removeCallbacks(menuTimer);
menuHandler.postDelayed(menuTimer, 5000);
bgHandler.removeCallbacks(runnableBG);
bgHandler.postDelayed(runnableBG, 2000);
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, GALLERY_REQUEST);
File file = getFileStreamPath("QuickPlayBG.png");
if (file.exists()) {
QPBackground.setImageBitmap(getThumbnail("QuickPlayBG.png"));
} else {
String uri21 = "#drawable/bg_green";
int imageResource21 = getResources().getIdentifier(uri21, null, getPackageName());
QPBackground.setBackgroundResource(imageResource21);
}
}
This sends you here:
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
Uri selectedImageUri;
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && null !=
data) {
selectedImageUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
cursor.close();
}
try {
Bundle extras = data.getExtras();
Bitmap photo = extras.getParcelable("data");
saveBGFile(photo);
} catch (Exception e) {
String errorMessage = "Make your mind up mate!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
try {
saveQPConfig();
} catch (IOException e) {
String errorMessage = "Saving failed";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
Which saves the file, using saveBGFile:
public void saveBGFile(Bitmap image) {
FileOutputStream out = null;
String filename = "QuickPlayBG.png";
try {
out = new FileOutputStream(filename);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The issue is with this line only:
QPBackground.setImageBitmap(getThumbnail("QuickPlayBG.png"));
It doesn't load anything. If I change "QuickPlayBG.png" to another filename that I am using in another part of my app, it loads fine. Both files are created using the same method. I verified that "QuickPlayBG.png" exists.
Compiler gives me the following hint:
E/﹕ ReadStreamToBuffer : Qmage Stream read error!! required length 12 bytes, but red 0 bytes
E/﹕ isQmage : input SkStreamRewindable length is less than Qmage minimum size : 0
I think it has to do with the way I am saving the image, but I cannot see the fault myself. What could be the problem, that it is not loading the image?
Edit:
Here is the getThumbnail method I am using (works for another filename):
public Bitmap getThumbnail(String filename) {
final Context context = this;
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath();
Bitmap thumbnail = null;
if (thumbnail == null) {
try {
File filePath = context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail() !exist", ex.getMessage());
}
}
return thumbnail;
}
Use this short and sweet code for this. use intent of gallery.
1.declaire variable.
private static int RESULT_IMG = 1;
String imgString;
2.call intent of gallery on onclick of button.
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
3.onActivityResult to your code.
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
try {
if (requestCode == RESULT_IMG && responseCode == RESULT_OK
&& null != data) {
Uri pickedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgString = cursor.getString(columnIndex);
cursor.close();
//set bitmap to your imageview
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory.decodeFile(imgString));
} else {
Toast.makeText(this, "please select picture",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "error message", Toast.LENGTH_LONG)
.show();
}
}

android: getting contact photo is not working, tried many things but still not working

In android i am trying to get contact data, i got success for number but for contact photo i am facing problem. i got contact photo uri content://com.android.contacts/data/6376/photo but when i am setting it to image view, the image view will blank
/*getting activity result */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
// return from file upload
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
Uri uri = data.getData();
String contactID="";
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.Contacts._ID
//ContactsContract.CommonDataKinds.Phone.p
}, null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
contactID = c.getString(2);
Bitmap photoBitmap = null;
Uri photo=null;
try {
photo = Uri.withAppendedPath(uri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageURI(photo);
// ImageView profile = (ImageView)findViewById(R.id.imageView1);
// Uri my_contact_Uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, contactID);
// InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(), my_contact_Uri);
// BufferedInputStream buf = new BufferedInputStream(photo_stream);
// Bitmap my_btmp = BitmapFactory.decodeStream(buf);
// profile.setImageBitmap(my_btmp);
} catch (Exception e) {
e.printStackTrace();
}
// contactNumber = cursor.getString(cursor.getColumnIndex((ContactsContract.CommonDataKinds.Phone.NUMBER)));
showSelectedNumber(type, number,contactID,photo.toString());
}
// Bitmap photo = null;
//
// try {
//
// InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
// ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));
//
//
//
// if (inputStream != null) {
// photo = BitmapFactory.decodeStream(inputStream);
// ImageView imageView = (ImageView) findViewById(R.id.imageView1);
// imageView.setImageBitmap(photo);
// }
//
// assert inputStream != null;
// inputStream.close();
//
// } catch (IOException e) {
// e.printStackTrace();
// }
}catch(Exception e){
Log.w(TAG,e+"");
} finally {
if (c != null) {
c.close();
}
}
}
}
} else {
Log.w(TAG, "Unknown Activity Result from add contact: "
+ resultCode);
}
}
}
in above code i have tried many things, like input stream etc. but still not getting photo of the contact but successful to get photo path.
When i am going to set data on image view it is not showing any thing on it.
If you already have the path, you could try this:
private void previewImage(String path) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 5; // setting the photo quality
final Bitmap bitmap = BitmapFactory.decodeFile(path, options);
photo.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
Retrieving thumbnail Image follow this code ..
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri,
new String[] {Contacts.Photo.PHOTO}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
Try out below code it will help you get contact number and its id and from that id number its will fetch the contact number.
public class DemoContact extends Activity {
private static final String TAG = DemoContact.class.getSimpleName();
private static final int REQUEST_CODE_PICK_CONTACTS = 1;
private Uri uriContact;
private String contactID, contactName; // contacts unique ID
private TextView m_contactName;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
m_contactName = (TextView) findViewById(R.id.textView1);
}
public void onClickSelectContact(View btnSelectContact) {
// using native contacts selection
// Intent.ACTION_PICK = Pick an item from the data, returning what was
// selected.
startActivityForResult(new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI),
REQUEST_CODE_PICK_CONTACTS);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_CONTACTS
&& resultCode == RESULT_OK) {
Log.d(TAG, "Response: " + data.toString());
uriContact = data.getData();
retrieveContactNumber();
retrieveContactPhoto();
m_contactName.setText("Contact Name: "+contactName);
}
}
//Retrieve the Contact photo based on the contactId
private void retrieveContactPhoto() {
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts
.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI,
new Long(contactID)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
ImageView imageView = (ImageView) findViewById(R.id.img_contact);
imageView.setImageBitmap(photo);
}
assert inputStream != null;
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//Get the contact number of the selected contact.
private void retrieveContactNumber() {
String contactNumber = null;
// getting contacts ID
Cursor cursorID = getContentResolver().query(uriContact,
new String[] { ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME }, null, null,
null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID
.getColumnIndex(ContactsContract.Contacts._ID));
contactName = cursorID.getString(cursorID .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursorID.close();
Log.d(TAG, "Contact ID: " + contactID);
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER },
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND "
+ ContactsContract.CommonDataKinds.Phone.TYPE + " = "
+ ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[] { contactID }, null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone
.getString(cursorPhone
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
Log.d(TAG, "Contact Phone Number: " + contactNumber);
}
}
OutPut:

Categories

Resources