0

这是我的代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button1 = (Button) findViewById(R.id.button1);

    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            MainActivity.this.runOnUiThread(new Runnable() {

                public void run() {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(
                            "http://shopstable.turkcell.com.tr/timmenu/getPerosConfig.do");
                    try {

                        HttpResponse response = httpclient
                                .execute(httppost);

                    } catch (ClientProtocolException e) {
                    } catch (IOException e) {
                    }
                }
            });
        }
    });

}

我收到 NetworkOnMainThreadException。我认为问题出在httppost中,但我无法弄清楚。

4

3 回答 3

1

当应用程序尝试在其主线程上执行网络操作时会引发此异常。仅针对针对Honeycomb SDK 或更高版本的应用程序会引发此异常。允许以早期 SDK 版本为目标的应用程序在其主事件循环线程上进行网络连接,但非常不鼓励这样做。在 AsyncTask 中运行您的代码:

于 2013-07-19T06:02:49.793 回答
0

您只需使用它即可获得解决方案:这里的 SDK 版本是您的应用程序的最低 sdk 版本..所以您必须在此处设置您的最低 sdk 版本。并将此代码放在 onCreate() 方法之后:

if (android.os.Build.VERSION.SDK_INT > 8) {

        StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(stp);

    }

并将此权限添加到您的清单文件中:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
于 2013-07-19T06:07:18.667 回答
0
 // use async task like this .this will solve ur problem


Class A{
 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button) findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                MainActivity.this.runOnUiThread(new Runnable() {

                    public void run() {
                      new RequestLogInFromServer().execute();

                    }
                });
            }
        });

    }




      public class RequestLogInFromServer extends AsyncTask<Object, Object, Object>
        {


            @Override
            protected Object doInBackground(Object... params)
            {

                String responsearray[] = new String[2];
            //JSONObject jsonResponse = null;


            // Create a new HttpClient and Post Header
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://shopstable.turkcell.com.tr/timme/getPerosConfig.do");
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            try {
                // Add your data

          in case if u want to pass any data to server else leave it

                List<NameValuePair> signinDetails = new ArrayList<NameValuePair>();
                signinDetails.add(new BasicNameValuePair("name",uname));
                signinDetails.add(new BasicNameValuePair("pass",pwd));

                httpPost.setEntity(new UrlEncodedFormEntity(signinDetails));

                // Execute HTTP Post Request
                HttpResponse httpResponse = httpClient.execute(httpPost);
                Log.v("Post Status", "Code: "
                        + httpResponse.getStatusLine().getStatusCode());
                responseCode = httpResponse.getStatusLine().getStatusCode();
                Log.e("responseBody", String.valueOf(responseCode));
                responsearray[0]=String.valueOf(responseCode);
                switch(responseCode){
                case 200:

                Log.e("responseCode", String.valueOf(responseCode));
                HttpEntity entity = httpResponse.getEntity();
                Log.e("entity", String.valueOf(entity));
                if (entity != null) {

                    responsearray[1] = EntityUtils.toString(entity);
                    Log.e("responsearray", String.valueOf(responsearray));


                /*  Log.e("responseBody", String.valueOf(responseBody));
                    JSONTokener jsonTokener = new JSONTokener(responseBody);
                    jsonResponse = new JSONObject(jsonTokener);
                    Log.e("finalResult", String.valueOf(jsonResponse));

                    JSONObject response = jsonResponse.getJSONObject("response");

                    // Getting String inside response object
                    String status = response.getString("status");
                    String message = response.getString("message");
                    Log.e("status", String.valueOf(status));
                    Log.e("message", String.valueOf(message));
                    */

                  } // if (entity != null)  end
                break;                  
                case 503:               
                    responsearray[1]="";

                break;

                default:
                    responsearray[1]="";            
                    break;


                }//switch end

            } catch (ClientProtocolException cpeExp) {
                // TODO Auto-generated catch block
            } catch (Exception allExp) {
                // TODO Auto-generated catch block
            }

            return responsearray;

            }


            @Override
            protected void onPostExecute(Object result) 
            {


                super.onPostExecute(result);
            }

            @Override
            protected void onPreExecute() {

                progressDialog = ProgressDialog.show(SignInActivity.this, "", "Please wait");
                super.onPreExecute();
            }

        }
} //close class A
于 2013-07-19T06:37:56.500 回答