修改视图的Internet任务 - CalledFromWrongThreadException

时间:2012-08-01 18:50:47

标签: java android

我想使用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:只有创建视图层次结构的原始线程才能触及其视图。

谢谢。

1 个答案:

答案 0 :(得分:0)

您需要调用修改UI线程视图的方法。 Painless threading可能是您的首选文章