仍然得到android.os.NetworkOnMainThreadException,我做错了什么?

时间:2014-11-06 15:56:02

标签: java android

试图从我们的MySql服务器上的php文件中获取一小部分信息,以显示应用程序的连接。此时它现在崩溃应用程序并吐出org.Apache.http.client.clientprotocolexecption,请原谅我,如果这是一个noob问题,我只用了4个月的java编程。

logcat的:

11-06 09:51:20.268: E/log.tag(2748): Error in http connection  org.apache.http.client.ClientProtocolException
    11-06 09:51:20.268: W/dalvikvm(2748): threadid=13: thread exiting with uncaught exception (group=0x40a13300)
    11-06 09:51:20.288: E/AndroidRuntime(2748): FATAL EXCEPTION: Thread-83
    11-06 09:51:20.288: E/AndroidRuntime(2748): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
    11-06 09:51:20.288: E/AndroidRuntime(2748):     at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4609)
    11-06 09:51:20.288: E/AndroidRuntime(2748):     at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:867)
    11-06 09:51:20.288: E/AndroidRuntime(2748):     at android.view.ViewGroup.invalidateChild(ViewGroup.java:4066)
    11-06 09:51:20.288: E/AndroidRuntime(2748):     at android.view.View.invalidate(View.java:10250)
    11-06 09:51:20.288: E/AndroidRuntime(2748):     at android.view.View.invalidate(View.java:10205)
    11-06 09:51:20.288: E/AndroidRuntime(2748):     at android.widget.TextView.checkForRelayout(TextView.java:6296)
    11-06 09:51:20.288: E/AndroidRuntime(2748):     at android.widget.TextView.setText(TextView.java:3547)
    11-06 09:51:20.288: E/AndroidRuntime(2748):     at android.widget.TextView.setText(TextView.java:3405)
    11-06 09:51:20.288: E/AndroidRuntime(2748):     at android.widget.TextView.setText(TextView.java:3380)
    11-06 09:51:20.288: E/AndroidRuntime(2748):     at com.mobile.donswholesale.AppInfo$1$1.run(AppInfo.java:111)
    11-06 09:51:20.288: E/AndroidRuntime(2748):     at java.lang.Thread.run(Thread.java:856)

代码:

test.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            new Thread(new Runnable() {

                public void run() {

                    try {

                        HttpParams httpParams = new BasicHttpParams();
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httpost = new HttpPost("http://"
                                + serverIp.getText().toString()
                                + "/mobile.php");
                        httpost.setHeader("Accept", "application/json");
                        HttpResponse response = httpclient.execute(httpost);
                        HttpEntity entity = response.getEntity();
                        isr = entity.getContent();
                    } catch (Exception e) {
                        Log.e("log.tag",
                                "Error in http connection  " + e.toString());
                        resultView.setText("Could not connect to Database");
                    }
                    try {
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(isr, "iso=8859-1"), 8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                        isr.close();

                        result = sb.toString();
                    } catch (Exception e) {
                        Log.e("log.tag",
                                "Error converting result  " + e.toString());
                    }

                    try {
                        String s = "";
                        JSONArray jArray = new JSONArray(result);
                        for (int i = 0; i < jArray.length(); i++) {
                            JSONObject json = jArray.getJSONObject(i);
                            s = s + "User :" + json.getString("UserName");
                        }
                        resultView.setText(s);
                    } catch (Exception e) {
                        Log.e("log.tag",
                                "Error Parsing Data " + e.toString());
                    }

                    Log.d(MainActivity.DEBUGTAG, "Didn't Work ");
                    return;
                }

                protected void onPostExecute(Void results) {

                }

            }).start();
        }

    });

2 个答案:

答案 0 :(得分:3)

您应该使用AsyncTask进行处理

      class A extends AsyncTask<Void, Void, String> {
          protected String doInBackground(Void... params) {
               String result = "";
               try {

                   HttpParams httpParams = new BasicHttpParams();
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httpost = new HttpPost("http://"
                            + serverIp.getText().toString()
                            + "/mobile.php");
                    httpost.setHeader("Accept", "application/json");
                    HttpResponse response = httpclient.execute(httpost);
                    HttpEntity entity = response.getEntity();
                    isr = entity.getContent();
                } catch (Exception e) {
                    Log.e("log.tag",
                            "Error in http connection  " + e.toString());
                    return null;
                    //resultView.setText("Could not connect to Database");
                }
                try {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(isr, "iso=8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    isr.close();

                    result = sb.toString();
                } catch (Exception e) {
                    Log.e("log.tag",
                            "Error converting result  " + e.toString());
                }

                try {
                    String s = "";
                    JSONArray jArray = new JSONArray(result);
                    for (int i = 0; i < jArray.length(); i++) {
                        JSONObject json = jArray.getJSONObject(i);
                        s = s + "User :" + json.getString("UserName");
                    }
                    return s;
                } catch (Exception e) {
                    Log.e("log.tag",
                            "Error Parsing Data " + e.toString());
                }
          }
          protected void onPostExecute(String s) {
               if (s == null) {
                    resultView.setText("Could not connect to Database");
               }
               else {
                   resultView.setText(s);
               }

}

然后简单地

test.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
         new A().execute();
    }
});

答案 1 :(得分:0)

您的问题是您正在尝试在UI线程外部的视图上设置文本。所以你已经为http访问创建了新的线程,现在你从同一个线程调用setText。如上所述,使用AsyncTask。