Programmatically setting ImageView resource not working

Viewed 212

I am trying to implement a feature where the user can select an image file from storage and that image gets displayed in a thumbnail-sized ImageView.

The file picking part seems to be correct:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, GET_ATTACHMENT_RESULT); 

//...

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GET_ATTACHMENT_RESULT){
        if (resultCode == RESULT_CANCELED){
            // Anything TODO here?
        } else if (resultCode == RESULT_OK){
            Uri uri = data.getData();

            addTimeFragment.onImageUrlReceived(uri);
        }
    }
}

The returning Uri appears to be a content Uri and has some path like:

content://com.android.providers.media.documents/document/image%3A14702

Calling uri.getPath() returns:

/document/image:14702

I have tried many different solutions found on numerous Stack Overflow posts involving Picasso (ideal solution), creating Bitmaps from various methods, setting the ImageView Uri, etc...

No Programmatic Method of Setting the ImageView Resource Works- even on PNGs located in my drawables. I can only successfully set the android:src in the XML.

Sanity Check:

  • The ImageView is visible, is constrained correctly, and has appropriate height and width.
  • I can set a source image in the xml and it appears. I also set the background color to make sure it's on screen. Everything is fine in XML.
  • I can also successfully programmatically set the ImageView background color so I know I am referencing the correct ImageView in code.

XML:

<ImageView
    android:id="@+id/thumbnail"
    android:layout_width="48dp"
    android:layout_height="48dp"
    app:layout_constraintTop_toBottomOf="@id/time_entry_spacer"
    app:layout_constraintStart_toStartOf="@id/camera_bg"
    android:layout_marginBottom="4dp"
    android:layout_marginStart="6dp"
    android:background="#220000FF"/> 

Assigning the ImageView:

//attachThumbnail is my ImageView
attachThumbnail = getActivity().findViewById(R.id.thumbnail);
attachThumbnail.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));  // This works as a sanity check

Various failures with the onImageUrlReceived Method:

public void onImageUrlReceived(Uri uri){
        Log.d(APP_TAG, "URI: " + uri.toString());
        Log.d(APP_TAG, "URI: " + uri.getPath());

// Even loading a known drawable fails
// Picasso.with(context).load(R.drawable.calendar).fit().error(R.drawable.error).into(attachThumbnail);


// Picasso.with(context).load(uri).fit().error(R.drawable.error).into(attachThumbnail);


// Picasso.with(context).load(uri.getPath()).fit().error(R.drawable.error).into(attachThumbnail);


//        File imgFile = new  File(url);
//        if(imgFile.exists()){
//            Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//
//            attachThumbnail.setImageBitmap(myBitmap);
//        }


//        attachThumbnail.setImageURI(uri);


//        Bitmap bitmap = null;
//        try {
//            bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        attachThumbnail.setImageBitmap(bitmap);


//        Bitmap b = BitmapFactory.decodeFile(uri.getPath());
//        attachThumbnail.setImageBitmap(b);


// See DownloadImage AsyncTask below
//        new DownloadImage(attachThumbnail).execute(uri.getPath());


// InputStream with scaling
//        try {
//            InputStream ims = getActivity().getContentResolver().openInputStream(uri);
//            Bitmap b = BitmapFactory.decodeStream(ims);
//            Bitmap b2 = Bitmap.createScaledBitmap(b, 50, 50, false);
//            attachThumbnail.setImageBitmap(b2);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }


// InputStream without Scaling
//        Bitmap bitmap = null;
//        try {
//            bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uri));
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        attachThumbnail.setImageBitmap(bitmap);
    }

    public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImage(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.d("Error", e.getStackTrace().toString());

            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }

Any other thoughts or insights here are greatly appreciated. I am definitely beating my head against a wall on this one.

Thanks.

1 Answers

I figured out the problem.

Because my ImageView was residing within a Fragment and not directly in the Activity, I was calling onImageUrlReceived(Uri uri) before onResume() was being called on my Fragment. onActivityResult is called before the Fragment resumes. As a result, the ImageView was being set correctly, but then a split second later, I was reassigning the ImageView when onResume was called so it would look like nothing was done.

As a result, I am now storing the Uri as a Fragment member and in onResume():

attachThumbnail = getActivity().findViewById(R.id.thumbnail);

if (userAttachmentUri != null){
    Picasso.with(getContext()).load(userAttachmentUri).fit().into(attachThumbnail);
}```
Related