I want to modify the TextViews of a tabbed Activity view using a TimerTask.
Here’s the code of the task class:
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...");
}
}
This is the class calling the task:
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;
}
}
This is the error:
08-01 20:43:16.759: E/AndroidRuntime(1030): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Thank you.
You need to call methods that modify views on the UI thread. Painless threading is probably your go-to article