NetworkOnMainThread异常 - 以正确的方式解析数据

时间:2014-10-10 19:15:37

标签: android android-asynctask

我开发了一个Android应用程序,用于将json数据集解析到我的应用程序中。但每次我获得NetworkOnMainThred异常时:

android.os.NetworkOnMainThreadException

在这一行:

HttpResponse response = httpclient.execute(httppost);

之后,我尝试通过puttin在AsyncTask内部类中进行修复。但是,这没有任何影响,我得到同样的错误。 AsyncTask真的很重要吗? 这里是整个背景:

question.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Connector db = new Connector();
            db.executeAction();//calls AsyncTask

        }
    });




public class Connector extends Activity {
    View rootView;
    ArrayList<String> resultset = new ArrayList<String>();
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }
public void executeAction() {
    new LongOperation().execute();
}

private class LongOperation extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        testDB2();
        return null;
    }
    public void testDB2() {

        String result = "";
        //the year data to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("year", "1980"));

        //http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://quizmaster.esy.es/db_con.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();

            result = sb.toString();
        } catch (Exception e) {
            //(TextView)rootView.findViewById(R.id.question)
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        ArrayList<String> resultset = new ArrayList<String>();
        //parse json data
        try {
            JSONArray jArray = new JSONArray(result);

            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                resultset.add(String.format(json_data.getString("Frage")));
                Log.i("log_tag", "id: " + json_data.getInt("ID") +
                                ", Frage: " + json_data.getString("Frage")
                );
            }
        }


        catch(JSONException e)
        {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
    }
    @Override
    protected void onPostExecute(String result) {

    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

}

调用:

public class Connector extends Activity { 
    View rootView; 
    ArrayList<String> resultset = new ArrayList<String>(); 

    /** Called when the activity is first created. */ 
    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
    } 

    public void executeAction() { 
        new LongOperation().doInBackground(); 
    }

1 个答案:

答案 0 :(得分:2)

您的onPostExecute()包含对testDB2()的调用。 onPostExecute()在主线程上执行。因此例外。

此外,您永远不会直接致电doInBackground()。相反,您将调用AsyncTask:

new LongOperation().execute();