2013-07-07 63 views
0

我有以下代碼:安卓:如何運行內的另一個任務(TimerTask的)任務

//Task that runs in background thread and posts results 
private class NewsWorkerTask extends AsyncTask<Void, Void, List<NewsData>> { 

    @Override 
    protected void onPreExecute() { 
    } 

    @Override 
    protected List<NewsData> doInBackground(Void... params) {   

     if (NewsDataProvider==null || NewsDataProvider.PageNumber ==0) 
     { 
      //Get New Data and initialize 
      NewsDataProvider = new NewsProvider(getActivity()); 
      return NewsDataProvider.GetTopNews(); 
     } 
     else 
     { 
      List<NewsData> tempDataList = NewsDataProvider.GetTopNews(); 

      // Merge new page 
      for (NewsData item : tempDataList) { 

       TopNewsDataList.add(item); 
      } 
     } 

     return null; 
    } 

    /* 
    * The system calls this to perform work in the UI thread and delivers 
    * the result from doInBackground() 
    */ 
    @Override 
    protected void onPostExecute(List<NewsData> data) { 

     final List<NewsData> tempDataList = data; 

     //Declare the timer 
     Timer t = new Timer(); 

     t.scheduleAtFixedRate(new TimerTask() { 

      @Override 
      public void run() { 
       //Called each time when 1000 milliseconds (1 second) (the period parameter) 
       if (tempDataList != null && tempDataList.size() > 0) { 

        if (tempDataList.size() == 1) { 
         TextView txtNewsTitle = (TextView)getView().findViewById(R.id.txtNewsTitle); 
         TextView txtNewsDate = (TextView)getView().findViewById(R.id.txtNewsDate); 
         txtNewsTitle.setText(tempDataList.get(0).DESCRIPTION); 
         txtNewsDate.setText(tempDataList.get(0).NEWS_DATE); 
        } 
        else { 
         TextView txtNewsTitle = (TextView)getView().findViewById(R.id.txtNewsTitle); 
         TextView txtNewsDate = (TextView)getView().findViewById(R.id.txtNewsDate); 
         txtNewsTitle.setText(tempDataList.get(newsIndex).DESCRIPTION); 
         txtNewsDate.setText(tempDataList.get(newsIndex).NEWS_DATE); 

         newsIndex++; 

         if (newsIndex == (tempDataList.size() - 1)) { 
          newsIndex = 0; 
         } 
        } 
       } 
      } 
     }, 
     //Set how long before to start calling the TimerTask (in milliseconds) 
     0, 
     //Set the amount of time between each execution (in milliseconds) 
     5000); 
    } 
} 

正如你可以看到TimerTask的運行在NewsWorkerTask

onPostExecute方法

我碰到下面的錯誤當我這樣做:

致命異常:定時器0 android.view.ViewRootImpl $ CalledFromWrongThreadException 只有創建視圖層次結構的原始線程可以觸及其視圖。

我把計時器在onPostExecute的原因是因爲我需要的時候,我得到的數據(GetTopNews()) GetTopNews基本上給我的十大最新的消息,我想顯示他們在一個盒子裏,以執行定時器每5秒切換到下一個新聞。

回答

1

嘗試使用

yourview.post(new Runnable() { 
     public void run() { 
//change your defined view here 
    } 
    }); 

內的TimerTask和更新上面的函數內部的意見!

相關問題