Image uploaded from gallery doesn't show in ImageView - android

I'm aware that there are several other questions on this topic but none of the solutions worked for me. I have added permissions in my manifest. I am able to open the gallery pick a photo and return to the application but the imageView does not change. The app is doing some processing and I am not getting any errors. I have tried also tried to scale the image before inserting it into my imageview with no luck.
Here is my code:
public class UserDetailsFragment extends Fragment {
private Context context;
private ImageView imageView;
private Bitmap uploadedImage;
public static final int RESULT_IMAGE = 0;
public UserDetailsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_user_details, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
imageView = (ImageView) getView().findViewById(R.id.profile_picture);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_IMAGE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
try {
InputStream in = new URL(filePath).openStream();
uploadedImage = BitmapFactory.decodeStream(in);
imageView.setImageBitmap(uploadedImage);
}catch (Exception ex){
}
}
}
}
Here is my imageView:
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="-160dp"
android:layout_gravity="center"
android:layout_below="#+id/imageView"
android:src="#drawable/user_details_icon"
android:id="#+id/profile_picture" />
EDIT
I tried to use Picasso instead but still no luck:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Picasso.with(context)
.load(MediaStore.Images.Media.DATA)
.resize(10, 10)
.centerCrop()
.into(imageView);
}

In Your previous code, the problem is in the following lines:
InputStream in = new URL(filePath).openStream();
uploadedImage = BitmapFactory.decodeStream(in);
these lines are creating exception because that is responsible for downloading image from server and covert it into Bitmap. As you are picking image from local storage, the path of image is something like following
/storage/emulated/0/DCIM/Camera/IMG_20170209_183830841.jpg
when you pass it in new URL() as a parameter, it creates following exception
java.net.MalformedURLException: Protocol not found
In your case first of all you need to add READ_EXTERNAL_STORAGE permission in your manifest file and in onActivityResult(), you have to replace
InputStream in = new URL(filePath).openStream();
uploadedImage = BitmapFactory.decodeStream(in);
with
File image = new File(filePath);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap, imageView.getWidth(), imageView.getHeight(), true);
Note: In case of marshmallow, don't forget to add security permission in your code.

I tried to use Picasso instead but still no luck:
That is because you are not using the correct Uri. You are using a Uri that points to the entire collection of scanned media.
If you read the documentation for ACTION_PICK, it has:
Output: The URI of the item that was picked.
Here, the Uri in question is obtained by calling getData() on the Intent delivered to onActivityResult().
So, replace .load(MediaStore.Images.Media.DATA) with .load(data.getData()).
Also, most likely, you need to increase the size of the image, as a 10px x 10px image is going to be rather small.

Related

Android Universal Image Loader fails to display image by uri

So my application works something like that:
In some point I switch to an activity that takes a photo, gets the created bitmap's url and passes it on to my main activity:
public class CameraActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
Intent mainmenu = new Intent(this, MainActivity.class);
mainmenu.putExtra("imageUri", imageUri.toString());
setResult(Activity.RESULT_OK, mainmenu);
finish();
}
}
Then in my main activity I update my sqlite db with the new path
switch(requestCode)
{
case CAMERA_RESULT:
String imageUri = data.getStringExtra("imageUri");
Task imageTask= tasks.get(taskImageSet);
db.deleteTask(imageTask);
adapter.remove(imageTask);
imageTask.setImagePath(imageUri);
db.addTask(imageTask);
adapter.add(imageTask);
adapter.notifyDataSetChanged();
break;
(I know it's kinda silly doing it like this but I just try to make the image loader thing work...)
Then when the user clicks on something it switches to another activity which supposed to show the result:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_showimage);
// UNIVERSAL IMAGE LOADER SETUP
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).build();
ImageLoader.getInstance().init(config);
String url = getIntent().getStringExtra("url");
Toast.makeText(this, url, Toast.LENGTH_LONG).show();
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.at_save)
.showImageOnFail(R.drawable.cv_fail)
.showImageOnLoading(R.drawable.cv_loading).build();
ImageView imageView = (ImageView) findViewById(R.id.ivTaskImage);
imageLoader.displayImage(url, imageView, options);
}
But it doesn't and instead it show the cv_fail image.
Important to mention that I printed the path when the bitmap generated and before showing the image and it was the same, looking something like:
content://media/external/images/media/84443
I have the following permission in my manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Any help would be very much appreciated!
Instead of using URI, you also can use file path of the image that you can retrieve from URI. The reason why I prefer to use file because you can check if the image is really exist in your storage or not. You can check all the acceptables URIs here : Universal Image Loader
Uri selectedImageUri = Uri.parse(imageUri);
String photoPath = getRealPathFromURI(selectedImageUri);
This is the method to get photo path
private String getRealPathFromURI(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Now you're getting result like this file:///mnt/sdcard/image.png. Then you can display the image as usual.
imageLoader.displayImage(photoPath, imageView, options);
//make sure your photoPath contain this prefix: 'file:/'

ImageView disappear after changed orientation

I have just started in developing in Android. So far I am learning stuff. I am stuck with this problem. In my onCreate method, i have a button to select an image in the device and the onActivityResult to get the image and display the image in an ImageView
After researching and looking for answers in the internet, someone advice that I am missing the onSaveInstanceState. so I created it. Here is my code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonLoadImage = (Button)findViewById(R.id.buttonLoadPicture);
targetImage = (ImageView) findViewById(R.id.imgView);
buttonLoadImage.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMG);
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putParcelable("BitmapImage", bitmap);
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
image = savedInstanceState.getParcelable("BitmapImage");
targetImage.setImageBitmap(image);
}
#Override
protected void onActivityResult( int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK){
Uri targetUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(targetUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
this.bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
targetImage.setImageBitmap(bitmap);
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
After building and running the code, selecting image and displaying it in ImageView works fine. When i change the orientation, image selected is still displayed. However when i rotate back again, the image displayed is gone.
Where am i doing wrong. Any advice and help is appreciated.
Are you storing 'bitmap' correctly? Here you are storing it to a local variable:
Bitmap bitmap;
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
targetImage.setImageBitmap(bitmap);
And here you are using a field:
savedInstanceState.putParcelable("BitmapImage", bitmap);
Looks like the field isn't being set so the onSaveInstanceState is storing a null value. Try removing Bitmap bitmap; or change bitmap = BitmapFactory... to this.bitmap = BitmapFactory.
EDIT:
Also try storing bitmap here:
image = savedInstanceState.getParcelable("BitmapImage");
targetImage.setImageBitmap(image);
By changing it to:
image = savedInstanceState.getParcelable("BitmapImage");
this.bitmap = image;
targetImage.setImageBitmap(this.bitmap);
I'm not sure what image is though as you haven't include the delcaration in the post.

Attach imageView to email

I want to attach imageView to send through Android mail services. This is how i get image from Gallery in Activity A:
public class Activity A extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_gallery);
private static int RESULT_LOAD_IMAGE = 1;
Button viewcards=(Button)findViewById(R.id.viewcards);
viewcards.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
{
Uri selectedImage = data.getData();
String[] filePathColumn =
{ MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Intent newdata = new Intent(SavedCards.this, Cardd.class);
newdata.putExtra("picture_path", picturePath);
startActivity(newdata);
}
}}
Transfer image to another class and and put imageView in Activity B:
public class Activity B extends Activity {
private ImageView cardimage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.carddd);
String temp = getIntent().getStringExtra("picture_path");
cardimage = (ImageView) findViewById(R.id.cardimage);
cardimage.setImageBitmap(BitmapFactory.decodeFile(temp));
and in Activity B, i want to attach this image into e-mail by onClick.
txtsend=(TextView) findViewById(R.id.txtsend);
txtsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
As a reference, how image can attach e-mail is here, but this is to pick from gallery.
How to do this by taken image which is already set on imageView. Thank you.
In your code you setup image to ImageView from file in Activity B. And you know path to this picture file. When you send email just attach this file.
Uri uri = Uri.parse("file://" + attachmentFile);
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
You can use ImageView's getDrawable method see this http://developer.android.com/reference/android/widget/ImageView.html#getDrawable()
So something like,
Bitmap imgViewBmp = ((BitmapDrawable)cardImage.getDrawable()).getBitmap();
Should work.
PS: I would suggest you to first check the api reference docs for any class you want to use. Chances of finding what you are looking for is quite high. Next best thing would be to actually google what you want to solve, if that doesn't work then "rephrase" you words and try again. The chances that you will find your solution are doubled (if not more) with the latter!

Imageview from phone galley

im trying to access and select an image from my phone galley onto my application imageView, using android. So far ive managed to set get to the galley and select the image i want to use, the only problem is that once ive selected the image i want i cant get it onto the imageview. the problem seems to be that ive got the imageview class seperate from my main class. ive checked and cant find a solution.
heres the code for the mediagalley class
public class MediaGallery extends Activity {
public static final int SELECT_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == SELECT_IMAGE) {
Uri selectedImage = data.getData();
String path = getPath(selectedImage);
Bitmap bitmapImage = BitmapFactory.decodeFile(path);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bitmapImage);
}
}
public String getPath(Uri uri) {
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, filePathColumn, null,null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
return cursor.getString(columnIndex);
}
}
and the main class code
case R.id.gallery_button:
MediaGallery activ1 = new MediaGallery();
Intent gallery = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, 1);
activ1.onActivityResult(1, 1, gallery);
break;
any help u gave give il be very greatful
You have declared MediaGallery is another Activity. Are you trying to show an ImageView on the same activity from which you select the button to launch the picker, or in a new activity? If the former, put that onActivityResult code into your main class. If the latter, then your main class should pass the Intent data to the MediaGallery class.

Delete/remove current image from ImageView?

I want to delete/remove or clear image from imageView every time when user again click to set another image to the imageView. i am getting OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=7239KB, Allocated=2769KB, Bitmap Size=8748KB)
here is my code:
ImageView imageView;
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
Bitmap yourSelectedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected void onResume() {
super.onResume();
imageView = (ImageView) findViewById(R.id.imageView);
((ImageView) findViewById(R.id.imageView))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
goToGallery();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
/*Toast.makeText(getBaseContext(), "" + selectedImagePath, 1000)
.show();
*///editText2.setText(selectedImagePath);
// Convert file path into bitmap image using below line.
yourSelectedImage = BitmapFactory
.decodeFile(selectedImagePath);
// put bitmapimage in your imageview
imageView.setImageBitmap(yourSelectedImage);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void goToGallery()
{
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
}
Setting a resource to 0 did not work for me. The following did work though:
imageView.setImageBitmap(null);
use the special resource Id '0'. It is not a valid res id, hence the image is blanked.
image.setImageDrawable(null);
will clear the image in the imageview.
When you set another image to the current ImageView the previous one is no longer used for the ImageView. Hence, no need to do extra work.
viewToUse.setImageResource(android.R.color.transparent);
I think using setImageResource with a color identifier will give you crashing issues on Android 2.2.1, make sure to test it.
edit_countflag.setBackgroundColor(0);

Categories

Resources