Adir Rahamim
Adir Rahamim

Reputation: 453

Set imageView from Thread

I am using a freind to download a picture and set in the ImageView; however, I get this error:

Only the original thread that created a view hierarchy can touch its views.

This is my code.

ImageView profilePicture =....
Thread thread = new Thread() {
    @Override
    public void run() {
        profilePic.setImageBitmap(image_profile);
    }
};
thread.start();

The image_profile Bitmap is a valid Bitmap file. (I checked it via debug.)

This thread is running in the OnCreate method.

Upvotes: 2

Views: 4219

Answers (3)

Raghunandan
Raghunandan

Reputation: 133560

You cannot update ui on another thread. Update ui on the main ui thread as below

Thread thread = new Thread()
{
    @Override
    public void run() {
    runOnUiThread(new Runnable() //run on ui thread
    {
        public void run() 
        { 
            profilePic.setImageBitmap(image_profile);

        }
    });
    }
    };
   thread.start();

Upvotes: 3

David Manpearl
David Manpearl

Reputation: 12656

You cannot update your UI directly from the Thread. Instead, use runOnUiThread() or equivalent.

Replace this:

profilePic.setImageBitmap(image_profile);

With this:

YourActivityName.this.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        profilePic.setImageBitmap(image_profile);
    }
});

Upvotes: 4

codeMagic
codeMagic

Reputation: 44571

The problem isn't about the Bitmap. The problem is that you are trying to do UI stuff in a separate Thread. With the code you've given, there is no reason for the Thread. Remove the Thread. If you are doing other things that you aren't showing then you can use runOnUiThread or an AsyncTask and update the ImageView in any method other than doInBackground() as it doesn't run on the UI

Upvotes: 1

Related Questions