1

I'm trying to set the bitmap image of an image view to a bitmap that is returned by another class, below is code snippet:-

imageView = (ImageView) findViewById(R.id.imageView);
Bitmap myBitmap = myModel.loadBitmap(getResources(), R.drawable.nether);
imageView.setImageBitmap(myBitmap);

Here's the model class:-

public class Model {

Bitmap cache;

public Bitmap loadBitmap(final Resources resource, final int i){

    new Thread(new Runnable(){
        public void run(){

            cache = BitmapFactory.decodeResource(resource, i);

        }
    }).start();

    return cache;
}
}

The problem is that the image doesn't display. It displays if the code used to load the bitmap is used before setting the image view bitmap in the same class but the returned bitmap doesn't work.

Any help would be great, thanks!

Hardy
  • 2,576
  • 1
  • 23
  • 45
AdamW95
  • 51
  • 1
  • 5
  • I would suggest to use a imageloading library like picassio or Universal Image loader – Illegal Argument Dec 09 '15 at 04:26
  • 1
    What is the question? – Apurva Dec 09 '15 at 04:27
  • woops, 4am problems.. the image isn't displaying however it works if the same code is used in the same class that the image view bitmap is set in, just the returned bitmap isn't working. – AdamW95 Dec 09 '15 at 04:30
  • don't create thread just use it as simple way because there may be posibility that thread run in background and when you call method cache value could be null – Hardy Dec 09 '15 at 04:31
  • The same code works fine from the same class as the image view bitmap is set though and the UI thread shouldn't really be used for decoding bitmaps – AdamW95 Dec 09 '15 at 04:33
  • Why not use an AsyncTask for this purpose? – Eric B. Dec 09 '15 at 04:36

2 Answers2

0

-You used thread which runs in background so it will not go in sequence and your cache may be return null thats why you were not able to set bitmap

Use this simple line for your problem :-

Bitmap bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.icon);
Hardy
  • 2,576
  • 1
  • 23
  • 45
  • yeah that works but using the same code with the same thread also works in the same class as the bitmap image is set, is there a way to get it to work by still using the thread? – AdamW95 Dec 09 '15 at 04:38
0

I managed to fix the problem and still keep the image loading inside the thread by passing the imageView:

  new Thread(new Runnable(){
        public void run(){

            cache = BitmapFactory.decodeResource(resource, i);

            imageView.post(new Runnable(){
                public void run(){
                    imageView.setImageBitmap(cache);
                }
            });

        }
    }).start();

Thanks for all your help!

AdamW95
  • 51
  • 1
  • 5