2012-06-18 61 views
0

我正在嘗試使用計時器刷新互聯網上的圖像。如何刷新網址並加載新圖像

這是我的代碼:

public class ProjectActivity extends Activity { 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    BannerActivity ba = new BannerActivity(this); 
    LinearLayout layout = (LinearLayout)findViewById(R.id.main_layout); 
    layout.addView(ba); 
} 

public class BannerActivity extends ImageButton implements OnClickListener{ 
    URL url = null; 
    public BannerActivity(Context context) { 
     super(context); 
     setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 300)); 
     loadimage(); 
     Timer timer = new Timer(); 
     timer.schedule(new TimerTask() { 
      public void run() { 
       loadimage(); 
      } 
      }, 5000, 1000); 
    } 

    private void loadimage(){ 
     try { 
      url = new URL("http://3.bp.blogspot.com/_9UYLMDqrnnE/S4UgSrTt8LI/AAAAAAAADxI/drlWsmQ8HW0/s400/sachin_tendulkar_double_century.jpg"); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } 
     InputStream content = null; 
     try { 
      content = (InputStream)url.getContent(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     final Drawable d = Drawable.createFromStream(content , "src"); 
     setBackgroundDrawable(d); 

     setOnClickListener(this); 
    } 

是我得到的錯誤是這樣的:

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

我是新來的這一點,不知道這意味着什麼或如何解決它。

回答

1

您正在試圖將UI變成非UI線程,這在Android中不可行。 Instaed od調用此方法setBackgroundDrawable(d);在你的Timer的run方法裏面,在runonUiThread()中包圍它。

contextObj.runOnUiThread(new Runnable() { 

     public void run() { 
      // TODO Auto-generated method stub 
      setBackgroundDrawable(d); 
     } 
    }); 

嘗試讓你的活動範圍,然後改變你的LoadImage()這樣的,

private void loadimage(){ 
    try { 
     url = new URL("http://3.bp.blogspot.com/_9UYLMDqrnnE/S4UgSrTt8LI/AAAAAAAADxI/drlWsmQ8HW0/s400/sachin_tendulkar_double_century.jpg"); 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } 
    InputStream content = null; 
    try { 
     content = (InputStream)url.getContent(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    final Drawable d = Drawable.createFromStream(content , "src"); 
    contextObj.runOnUiThread(new Runnable() { 

     public void run() { 
      // TODO Auto-generated method stub 
      setBackgroundDrawable(d); 
     } 
    }); 


    setOnClickListener(this); 
} 
+1

很棒!它工作..我只需要添加一個演員: 上下文contextObj = getContext(); \t \t((Activity)contextObj).runOnUiThread(new Runnable(){ – roiberg

+0

高興它幫助你:).. –

0

Activity類是一個線程。如果你嘗試在沒有Handler的情況下創建線程,它會給出ThreadException。所以,添加一個Handler來處理這個新線程。

謝謝