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);
}
}
당신이 NewsWorkerTask
의 onPostExecute 방법에 TimerTask를 실행을 볼 수 있듯이을치명적인 예외 : 타이머 0나는이 작업을 수행 할 때
는 나는 다음과 같은 오류가 발생합니다android.view.ViewRootImpl $ CalledFromWrongThreadException 뷰 계층 구조를 만든 원래 스레드 만 해당 뷰를 만질 수 있습니다.
내가 데이터 (GetTopNews을()) GetTopNews 기본적으로 나에게 10 최신 뉴스를 제공합니다 나는 상자 안에 그들을 표시 할 얻을 때 타이머를 실행해야하기 때문에 나는 onPostExecute에 타이머를 넣어 그 이유는5 초마다 다음 뉴스로 전환합니다.