2015-04-12 35 views
0

我希望我的頁面顯示圖像,但是當我運行它時,出現錯誤:「只有創建視圖層次結構的原始線程可以觸摸它意見」,任何人都可以告訴我如何解決它在這裏是我的代碼:?只有創建視圖層次結構的原始線程可以觸及其視圖android

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; 
} 

} 

回答

1

不能調用image.setImageBitmap(bitmap);Thread以外的主線程。

理想情況下,您應該使用AsyncTask或某種機制,您可以將回調接口傳遞給主線程並設置位圖。但對於一個快速和骯髒的解決方案試試這個:

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(); 
+0

你能告訴我如何修改我的代碼? – Stu

+0

顯示「活動」? – Anyonymous2324

+0

yourActivityObject引用了什麼?對不起,我是Android新手。 – Stu

相關問題