Simple change of an ImageView in Android - android

I am new at this :)
I am trying to load a picture from the sdcard into an ImageView in this way:
b_picture.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}
});
Here I am trying to retrive the picture and change the ImageView:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm = (Bitmap) data.getExtras().get("data");
iv_picture.setImageBitmap(bm);
}
And I get this from the logcat:
Failure delivering result ResultInfo {who=null, request=0, result=-1,
data=Intent { dat=content://media/external/images/media/2
I can't solve this problem. Can you help me? Thanks.

The data associated with your returned Intent is not a bitmap. It's a URI you can use to look up in the MediaStore ContentProvider to get back the image you want. :)
You can find a mostly-working example over at this question.
Edit: To expand:
When you go off and query the MediaStore for an image, it isn't returning you the actual image. It's returning you a URI that you can use to look up the image. The way you translate that URI into an actual image is this:
Your URI is content://media/external/images/media/2 as per the error message.
So, we'll basically create a query and run it on the MediaStore's ContentProvider, which is a database of images. Pass that URI into this function:
public Bitmap loadFullImage( Context context, Uri photoUri ) {
Cursor photoCursor = null;
try {
// Attempt to fetch asset filename for image
// DATA is the column name in the database for the filename of the image
String[] projection = { MediaStore.Images.Media.DATA };
// use the URI you were given in order to look up the right image,
// and get a Cursor object that will iterate over the matching rows in the
// database.
photoCursor = context.getContentResolver().query( photoUri,
projection, null, null, null );
// since we only care about one image...
if ( photoCursor != null && photoCursor.getCount() == 1 ) {
// go to the first row that was returned
photoCursor.moveToFirst();
// get the string in the DATA column at that row
String photoFilePath = photoCursor.getString(
photoCursor.getColumnIndex(MediaStore.Images.Media.DATA) );
// Load image from path
return BitmapFactory.decodeFile( photoFilePath, null );
}
} finally {
// close up the cursor
if ( photoCursor != null ) {
photoCursor.close();
}
}
return null;
}

// path ex: /sdcard/myimage.png
String imageInSD = "Your image path here";
BitmapFactory.Options bOptions = new BitmapFactory.Options();
bOptions.inTempStorage = new byte[16*1024];
bitmap = BitmapFactory.decodeFile(imageInSD,bOptions);
imageView.setImageBitmap(bitmap);

Related

Issues with BitmapFactory.decodeFile when i pick a picture

When i pick a picture the BitmapFactory.decodeFile returns null.
Here is my function:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath,options);
//imageView.setImageBitmap(bitmap);
// Do something with the bitmap
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}
Can somebody tell me what is the issue?
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
do you have the filePath in the variable imagePath ? or is imagePath value is null too ?
UPDATE
your BitmapFactory.decodeFile() is returning null because may be the imageSize is too big and its throwing some exception.
check your log and see if there is any outOfMemory Bitmap error is there . let me know

Android how to pick up images from Lollipop / Marshmallow and save it on imageView?

I tried that code and gave me error unable to decode stream filenotfoundException. So I found that the latest versions of Android Marshmallow and lollipop doesn't have the gallery application and the images uploaded to a server.
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(column_index);
return picturePath;
}
// this is our fallback here
return uri.getPath();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
ImageView imageView = (ImageView) findViewById(R.id.profile_picture);
imageView.setImageBitmap(BitmapFactory.decodeFile(getPath(selectedImageUri)));
}
}
}
My intent code:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
Step #1: Get rid of getPath().
Step #2: Use an image-loading library, such as Picasso. Pass it the Uri you get from the Intent passed into onActivityResult(), and your ImageView. It will handle loading the image into the ImageView for you.
If you would prefer to load the image yourself, you will need to:
Use a ContentResolver and openInputStream() to get an InputStream for the data represented by the Uri
Use BitmapFactory.decodeStream() to load the data off the InputStream and decode it into a Bitmap
Do the above steps in a background thread, so you do not tie up the main application thread while doing that I/O (e.g., doInBackground() of an AsyncTask)
When the Bitmap is ready, put it in the ImageView while running on the main application thread (e.g., onPostExecute() of an AsyncTask)

Pick image from gallery, including Picasa/AutoBackup images

I am dealing with Pick gallery images and show them in app also save their Path for some references in future.
I was able to Pick those images from gallery which are stored on device like in some folder like Downloads by this code:
Intent intent = new Intent (Intent.ActionPick, Android.Provider.MediaStore.Images.Media.ExternalContentUri);
intent.SetType ("image/*");
StartActivityForResult (Intent.CreateChooser (intent, "Select photo"), 0);
and in Result:
public override void OnActivityResult (int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult (requestCode, resultCode, data);
case 0:
string FilePath = GetPathToImage (data.Data);
}
private string GetPathToImage(Android.Net.Uri uri)
{
string path = null;
string[] projection = new[] { Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data };
using (ICursor cursor = this.Activity.ManagedQuery(uri, projection, null, null, null))
{
if (cursor != null)
{
int columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
cursor.MoveToFirst();
path = cursor.GetString(columnIndex);
}
else
{
return uri.Path;
}
}
}
My question is : I am able to get paths of images those are placed in some local folder in gallery, but for folders like Picasa/Autobackup I am not able to get Path.
Note:For local images path starts from content://
For Other com.android....like that.
So, Is there any workaround to get paths of those images.
I don't want to do like this to just display image:
final InputStream is = getContentResolver().openInputStream(imageUri);
I need a Path.
If there is no solution, then How can we skip those images being displayed while Picking from Gallery/Photos.
PS: Known Issue
Any Suggestion is appreciated.
Thanks

Get only gallery folder : Intent.ACTION_GET_CONTENT

I would like to implement a Picture Chooser, since there's a bug with the Recent image foler and the Download Folder the Android app crashes when selecting an image from these two folders, I would like to hide them, or open directly the Gallery folder without showing the Folder chooser panel,
This is my actual code :
Intent intent = new Intent (Intent.ACTION_GET_CONTENT);
startActivityForResult (intent, 1000);
and in the on Result Method :
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent intent) {
super.onActivityResult (requestCode, resultCode, intent);
String uri = intent.getDataString ();
String absolutePath = getRealPathFromURI (uri);
String compressedFilePath = compressImage (absolutePath);
encodedResult = base64File (new File (compressedFilePath)); //String
}
protected String getRealPathFromURI (String contentURI, UIView uiView) {
Uri contentUri = Uri.parse(contentURI);
Cursor cursor = ((ContextWrapper) uiView).getContentResolver ().query(contentUri, null, null, null, null);
if (cursor == null) {
return contentUri.getPath();
} else {
cursor.moveToFirst();
int index = cursor.getColumnIndex(MediaColumns.DATA);
return cursor.getString(index);
}
}
So when I select an image from a folder like : Gallery, Pictures etc... It works just fine. But for the 2 folders : Download and Recent it crashes and gives me :
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Or maybe there is a more correct way of doing that which I'm not aware of it ?
Do you have any idea about this ? How can I achieve that ? Thanks.
it crashes and gives me
That is because you are assuming that any Uri can be converted into a File. That has never been supported.
Use a ContentResolver and consume the Uri via openInputStream() (or openOutputStream(), if appropriate).

Retrieve Picasa Image for Upload from Gallery

I am working on an activity and associated tasks that allow users to select an image to use as their profile picture from the Gallery. Once the selection is made the image is uploaded to a web server via its API. I have this working regular images from the gallery. However, if the image selected is from a Picasa Web Album nothing is returned.
I have done a lot of debugging and narrowed the problem down to this method.
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
//cursor is null for picasa images
if(cursor!=null)
{
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else return null;
}
Picasa images return a null cursor. MediaStore.Images.Media.DATA is not null for them, however. It only returns an #id, so I am guessing that there is no actual bitmap data at the address. Are Picasa images stored locally on the device at all?
I also noticed from the documentation that MediaStore.Images.ImageColumns.PICASA_ID exists. This value exists for selected picasa images but not other gallery images. I was thinking I could use this value to get a URL for the image if it is not store locally but I can not find any information about it anywhere.
I have faced the exact same problem,
Finally the solution I found, was to launch an ACTION_GET_CONTENT intent instead of an ACTION_PICK, then make sure you provide a MediaStore.EXTRA_OUTPUT extra with an uri to a temporary file.
Here is the code to start the intent :
public class YourActivity extends Activity {
File mTempFile;
int REQUEST_CODE_CHOOSE_PICTURE = 1;
(...)
public showImagePicker() {
mTempFile = getFileStreamPath("yourTempFile");
mTempFile.getParentFile().mkdirs();
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempFile));
intent.putExtra("outputFormat",Bitmap.CompressFormat.PNG.name());
startActivityForResult(intent,REQUEST_CODE_CHOOSE_PICTURE);
}
(...)
}
You might need to mTempFile.createFile()
Then in onActivityResult, you will be able to get the image this way
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
case REQUEST_CODE_CHOOSE_PICTURE:
Uri imageUri = data.getData();
if (imageUri == null || imageUri.toString().length() == 0) {
imageUri = Uri.fromFile(mTempFile);
file = mTempFile;
}
if (file == null) {
//use your current method here, for compatibility as some other picture chooser might not handle extra_output
}
}
Hope this helps
Then you should delete your temporary file on finish (it is in internal storage as is, but you can use external storage, I guess it would be better).
Why are you using the managedQuery() method? That method is deprecated.
If you want to convert a Uri to a Bitmap object try this code:
public Bitmap getBitmap(Uri uri) {
Bitmap orgImage = null;
try {
orgImage = BitmapFactory.decodeStream(getApplicationContext().getContentResolver().openInputStream(uri));
} catch (FileNotFoundException e) {
// do something if you want
}
return orgImage;
}

Categories

Resources