0

Here is my code:

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

}

i'am getting NetworkOnMainThreadException. I think the problem is in the httppost, but i couldn't figure it out.

416E64726577
  • 2,214
  • 2
  • 23
  • 47
mstfdz
  • 2,616
  • 3
  • 23
  • 27

3 Answers3

1

This exception is thrown when an application attempts to perform a networking operation on its main thread.This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. Run your code in AsyncTask:

0

you have simply use this so get solution: Here SDK version is your app's minimum sdk version ..so you have to set your minimum sdk version here. And put this code after onCreate() method:

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

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

    }

And also add this permission to your manifest file:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Shani Goriwal
  • 2,111
  • 1
  • 18
  • 30
  • please dont use strictmode because it is for only testing purpose.if u use strict mode ur code says to android that dont show me any error instead run by excluding all warning and system errors.once ur app gonna reach market then u should not use strict mode. – Ruban Jul 19 '13 at 06:39
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
Ruban
  • 1,514
  • 2
  • 14
  • 21