在AsyncTask onPostExecute中出现NetworkOnMainThreadException错误

时间:2014-02-10 18:41:07

标签: android android-asynctask bufferedreader stringbuilder

我有异步任务来获取json数组加载微调器。但在onPostExecute我得到了 NetworkOnMainThreadException错误。

//这里的错误

 while ((line = reader.readLine()) != null) 
 {
  builder.append(line) ;
 }

这是我的onPostExecute。响应是一个Http响应。这里有什么错误?

   protected void onPostExecute(String result) {

             BufferedReader reader;
            try {
    reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                 StringBuilder builder = new StringBuilder();

                 String line = null;

                    //Error in here
                 while ((line = reader.readLine()) != null) 
                    {
                     builder.append(line) ;
                    }



                 JSONTokener tokener = new JSONTokener(builder.toString());
                 JSONArray finalResult = new JSONArray(tokener);

                 final String[] items = new String[finalResult.length()]; 

                    // looping through All Contacts
                    for(int i = 0; i < finalResult.length(); i++){

                        JSONObject c = finalResult.getJSONObject(i);

                        items[i]=c.getString("data_name");

                    }

                    ArrayAdapter<String> adapter = new ArrayAdapter<String> (activity, android.R.layout.simple_spinner_item, items);       

                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                    spin.setAdapter(adapter);



            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } 


            super.onPostExecute(result);

            //activity.startActivity(new Intent(activity, wanted.class));


            if (dialog != null)
                 dialog.dismiss();   

        }

1 个答案:

答案 0 :(得分:3)

你应该移动你的:

reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// ..
while ((line = reader.readLine()) != null) 

AsyncTask.doInBackground()

这是必须进行网络操作的地方,onPostExecute在UI线程上