0

I want my page to show an image, but when I run it, get the error: "Only the original thread that created a view hierarchy can touch its views" , could anyone tell me how to fix it?here is my code:

show.java:

public class Show extends Base{

String nameValue, style_of_cookingValue, ingredientValue, stepValue, imageValue, costValue;
TextView name, style_of_cooking, ingredient, step, cost;
ImageView image;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recipe);


    nameValue = getIntent().getStringExtra("name");
    style_of_cookingValue = getIntent().getStringExtra("style_of_cooking");
    ingredientValue = getIntent().getStringExtra("ingredient");
    stepValue = getIntent().getStringExtra("step");
    costValue = getIntent().getStringExtra("cost");
    imageValue = getIntent().getStringExtra("image");

    name = (TextView) findViewById(R.id.nameContent);
    style_of_cooking = (TextView) findViewById(R.id.typeContent);
    ingredient = (TextView) findViewById(R.id.ingredientContent);
    step = (TextView) findViewById(R.id.stepContent);
    cost = (TextView) findViewById(R.id.costContent);
    image = (ImageView) findViewById(R.id.image);

    name.setText(nameValue);
    style_of_cooking.setText(style_of_cookingValue);
    ingredient.setText(ingredientValue);
    step.setText(stepValue);
    cost.setText(costValue);

    new Thread(new Runnable(){
        public void run() {
            try {
              Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageValue).getContent());
              image.setImageBitmap(bitmap); 
            } catch (MalformedURLException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            }
        }
    }).start();
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            break;
    }
    return true;
}

}
Stu
  • 3
  • 3

1 Answers1

1

You cannot call image.setImageBitmap(bitmap); inside a Thread other than the main thread.

Ideally you should use an AsyncTask or some sort of mechanism where you can pass a callback interface to the main thread and set the bitmap. But for a quick and dirty solution try this:

new Thread(new Runnable(){
    public void run() {
        try {
          Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageValue).getContent());
          Show.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                image.setImageBitmap(bitmap); 
            }
        }); 
        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
    }
}).start();
Anyonymous2324
  • 250
  • 3
  • 12