我想使用TimerTask修改选项卡式Activity视图的TextView 这是任务类的代码:
public class QueryServer extends TimerTask {
public void run(){
MCQuery mcQuery = new MCQuery(serverAddrress,25565);
QueryResponse response = mcQuery.basicStat();
int Onlineplayers = response.getOnlinePlayers();
int MaxPlayers = response.getMaxPlayers();
Log.d("MCQuery", "" + Onlineplayers + " OnlinePlayers");
TextView serverStatus = (TextView) findViewById(R.id.server_status);
TextView onlinePlayersView = (TextView) findViewById(R.id.online_players);
serverStatus.setText("Online");
onlinePlayersView.setText("" + Onlineplayers + "/" + MaxPlayers);
Log.d("QueryServer", "Querying the server...");
}
}
这是调用任务的类:
public class FirstTab extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_tab, null);
//check Internet connection
if (isOnline() == true) {
Log.d("CheckConnection", "The device is connected to the network");
} else {
Log.d("CheckConnection", "The device is NOT connected to the network");
}
Timer timer = new Timer();
TimerTask task = new QueryServer();
//run the QueryServer task every 3 seconds
timer.schedule(task, 3000, 3000);
return v;
}
}
这是错误:
08-01 20:43:16.759:E / AndroidRuntime(1030):android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。
谢谢。