仍然得到android.os.NetworkOnMainThreadException,我究竟做错了什么? [英] still getting android.os.NetworkOnMainThreadException, what am I doing wrong?

查看:210
本文介绍了仍然得到android.os.NetworkOnMainThreadException,我究竟做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想抓住的一小段信息从我们的MySQL服务器上的PHP文件显示是由应用程序建立连接。在这一点上,现在崩溃的应用程序,并吐出org.Apache.http.client.clientprotocolexecption,原谅我,如果这是一个noob问题,我只有4个月后在Java编程。

logcat的:

  9月11日至6日:51:20.268:E / log.tag(2748):在http连接org.apache.http.client.ClientProtocolException错误
    9月11日至六日:51:20.268:W / dalvikvm(2748):主题ID = 13:螺纹未捕获的异常退出(组= 0x40a13300)
    9月11日至六日:51:20.288:E / AndroidRuntime(2748):致命异常:螺纹83
    9月11日至六日:51:20.288:E / AndroidRuntime(2748):android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次可以触摸其观点原来的线程。
    9月11日至六日:51:20.288:E / AndroidRuntime(2748):在android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4609)
    9月11日至六日:51:20.288:E / AndroidRuntime(2748):在android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:867)
    9月11日至六日:51:20.288:E / AndroidRuntime(2748):在android.view.ViewGroup.invalidateChild(ViewGroup.java:4066)
    9月11日至六日:51:20.288:E / AndroidRuntime(2748):在android.view.View.invalidate(View.java:10250)
    9月11日至六日:51:20.288:E / AndroidRuntime(2748):在android.view.View.invalidate(View.java:10205)
    9月11日至六日:51:20.288:E / AndroidRuntime(2748):在android.widget.TextView.checkForRelayout(TextView.java:6296)
    9月11日至六日:51:20.288:E / AndroidRuntime(2748):在android.widget.TextView.setText(TextView.java:3547)
    9月11日至六日:51:20.288:E / AndroidRuntime(2748):在android.widget.TextView.setText(TextView.java:3405)
    9月11日至六日:51:20.288:E / AndroidRuntime(2748):在android.widget.TextView.setText(TextView.java:3380)
    9月11日至六日:51:20.288:E / AndroidRuntime(2748):在com.mobile.donswholesale.AppInfo $ 1 $ 1.run(AppInfo.java:111)
    9月11日至六日:51:20.288:E / AndroidRuntime(2748):在java.lang.Thread.run(Thread.java:856)

code:

  test.setOnClickListener(新View.OnClickListener(){        @覆盖
        公共无效的onClick(视图v){            新主题(新的Runnable接口(){                公共无效的run(){                    尝试{                        的HttpParams的HttpParams =新BasicHttpParams();
                        HttpClient的HttpClient的=新DefaultHttpClient();
                        HttpPost httpost =新HttpPost(HTTP://
                                + serverIp.getText()。的toString()
                                +/mobile.php);
                        httpost.setHeader(接受,应用/ JSON);
                        HTT presponse响应= httpclient.execute(httpost);
                        HttpEntity实体= response.getEntity();
                        ISR = entity.getContent();
                    }赶上(例外五){
                        Log.e(log.tag
                                错误http连接+ e.toString());
                        resultView.setText(无法​​连接到数据库);
                    }
                    尝试{
                        读者的BufferedReader =新的BufferedReader(
                                新的InputStreamReader(ISR,异= 8859-1),8);
                        StringBuilder的SB =新的StringBuilder();
                        串线= NULL;
                        而((行= reader.readLine())!= NULL){
                            sb.append(行+\\ n);
                        }
                        isr.close();                        结果= sb.toString();
                    }赶上(例外五){
                        Log.e(log.tag
                                错误转换结果+ e.toString());
                    }                    尝试{
                        字符串s =;
                        JSONArray jArray =新JSONArray(结果);
                        的for(int i = 0; I< jArray.length();我++){
                            JSONObject的JSON = jArray.getJSONObject(I)
                            S = S +用户:+ json.getString(用户名);
                        }
                        resultView.setText(多个);
                    }赶上(例外五){
                        Log.e(log.tag
                                错误解析数据+ e.toString());
                    }                    Log.d(MainActivity.DEBUGTAG,没有工作);
                    返回;
                }                保护无效onPostExecute(无效的结果){                }            })。开始();
        }    });


解决方案

你应该使用的AsyncTask的进程

  A级扩展的AsyncTask<太虚,太虚,字符串> {
          保护字符串doInBackground(虚空...... PARAMS){
               字符串结果=;
               尝试{                   的HttpParams的HttpParams =新BasicHttpParams();
                    HttpClient的HttpClient的=新DefaultHttpClient();
                    HttpPost httpost =新HttpPost(HTTP://
                            + serverIp.getText()。的toString()
                            +/mobile.php);
                    httpost.setHeader(接受,应用/ JSON);
                    HTT presponse响应= httpclient.execute(httpost);
                    HttpEntity实体= response.getEntity();
                    ISR = entity.getContent();
                }赶上(例外五){
                    Log.e(log.tag
                            错误http连接+ e.toString());
                    返回null;
                    //resultView.setText(\"Could无法连接到数据库);
                }
                尝试{
                    读者的BufferedReader =新的BufferedReader(
                            新的InputStreamReader(ISR,异= 8859-1),8);
                    StringBuilder的SB =新的StringBuilder();
                    串线= NULL;
                    而((行= reader.readLine())!= NULL){
                        sb.append(行+\\ n);
                    }
                    isr.close();                    结果= sb.toString();
                }赶上(例外五){
                    Log.e(log.tag
                            错误转换结果+ e.toString());
                }                尝试{
                    字符串s =;
                    JSONArray jArray =新JSONArray(结果);
                    的for(int i = 0; I< jArray.length();我++){
                        JSONObject的JSON = jArray.getJSONObject(I)
                        S = S +用户:+ json.getString(用户名);
                    }
                    返回S;
                }赶上(例外五){
                    Log.e(log.tag
                            错误解析数据+ e.toString());
                }
          }
          保护无效onPostExecute(String s)将{
               如果(S == NULL){
                    resultView.setText(无法​​连接到数据库);
               }
               其他{
                   resultView.setText(多个);
               }}

,然后简单地

  test.setOnClickListener(新View.OnClickListener(){    @覆盖
    公共无效的onClick(视图v){
         新A()的execute()。
    }
});

Just trying to grab a small bit of information from a php file on our MySql server to show a connection was made by the app. At this point it now crashes the app and spit out org.Apache.http.client.clientprotocolexecption, forgive me if this is a noob question, I'm only 4 months into programing in 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)

Code:

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();
        }

    });

解决方案

you should use AsyncTask for the process

      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);
               }

}

and then simply

test.setOnClickListener(new View.OnClickListener() {

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

这篇关于仍然得到android.os.NetworkOnMainThreadException,我究竟做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆