如何解决mainthread的问题

时间:2014-01-24 17:49:14

标签: android json multithreading network-connection

我尝试从php文件中获取JSON数据

public void connect(){
    System.out.println("%%%%%%%%%%%%%%%%%1" );
    Thread t = new Thread(){

        @Override
        public void run() {

    try {

        System.out.println("%%%%%%%%%%%%%%%%%2" );
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(params, 0);
        HttpClient httpClient = new DefaultHttpClient(params);
        String urlString = "http://url";
        //prepare the HTTP GET call 
        HttpGet httpget = new HttpGet(urlString);
        //get the response entity
        HttpEntity entity = httpClient.execute(httpget).getEntity();
        System.out.println("%%%%%%%%%%%%%%%%%3" );
        if (entity != null) {
            //get the response content as a string
            String response = EntityUtils.toString(entity);
            //consume the entity
            entity.consumeContent();

            // When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();

            //return the JSON response

            JSONArray jsonarray = new JSONArray(response); 
            JSONObject jb =(JSONObject) jsonarray.getJSONObject(0);
            String name= jb.getString("name");
            String punkt = jb.getString("punktezahl");

             //String name = jsonarray.getString("name");
             System.out.println("HEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + name);
             fuehrender.setText(name);
             punkte.setText(punkt);
               }



    }catch (Exception e) {
        e.printStackTrace();
    }
}

};
t.start();
}

如果我这样做,我会收到消息,只有创建视图层次结构的原始线程才能触及其视图。

因此,由于此错误消息,我尝试了这样:

public void connect(){
    System.out.println("%%%%%%%%%%%%%%%%%1" );
    runOnUiThread(new Runnable() {

        @Override
        public void run() {

    try {

        System.out.println("%%%%%%%%%%%%%%%%%2" );
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(params, 0);
        HttpClient httpClient = new DefaultHttpClient(params);
        String urlString = "http://url";
        //prepare the HTTP GET call 
        HttpGet httpget = new HttpGet(urlString);
        //get the response entity
        HttpEntity entity = httpClient.execute(httpget).getEntity();
        System.out.println("%%%%%%%%%%%%%%%%%3" );
        if (entity != null) {
            //get the response content as a string
            String response = EntityUtils.toString(entity);
            //consume the entity
            entity.consumeContent();

            // When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();

            //return the JSON response

            JSONArray jsonarray = new JSONArray(response); 
            JSONObject jb =(JSONObject) jsonarray.getJSONObject(0);
            String name= jb.getString("name");
            String punkt = jb.getString("punktezahl");

             //String name = jsonarray.getString("name");
             System.out.println("HEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + name);
             fuehrender.setText(name);
             punkte.setText(punkt);
               }



    }catch (Exception e) {
        e.printStackTrace();
    }
}

});

}
}

现在,我收到NetworkOnMainThread错误消息..如何突破这个厄运循环?

1 个答案:

答案 0 :(得分:1)

你有runOnUiThread。去掉它。它应该仅用于更新ui而不是用于http get请求。

使用AsyncTask是更好的选择。在doInBackground中创建http get请求并解析响应。您可以将结果返回doInbackground,这是onPostExecute的参数。

所以你可以更新在ui线程上调用的onPostExecute中的ui。

http://developer.android.com/reference/android/os/AsyncTask.html

示例:

调用

new TheTask().execute(); // in ui thread

AsyncTask成为内部活动类

class TheTask extends AsyncTask<Void,Void,String>
{

    @Override
    protected String doInBackground(Void... params1) {
        String response = null; 
            try {
                HttpParams params = new BasicHttpParams();
                HttpConnectionParams.setSoTimeout(params, 0);
                HttpClient httpClient = new DefaultHttpClient(params);
                String urlString = "http://url";
                HttpGet httpget = new HttpGet(urlString);
                HttpEntity entity = httpClient.execute(httpget).getEntity();
                response = EntityUtils.toString(entity);
                httpClient.getConnectionManager().shutdown();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
         JSONArray jsonarray = new JSONArray(result; 
         JSONObject jb =(JSONObject) jsonarray.getJSONObject(0);
         String name= jb.getString("name");
         String punkt = jb.getString("punktezahl");
         fuehrender.setText(name);
         punkte.setText(punkt);
    }

}