android.os.NetworkOnMainThreadException with android 4.2

This question already has an answer here:

  • How do I fix android.os.NetworkOnMainThreadException? 49 answers

  • Write below code into your MainActivity file after setContentView(R.layout.activity_main);

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    

    And below import statement into your java file.

    import android.os.StrictMode;
    

    This is the correct way:

    public class JSONParser extends AsyncTask <String, Void, String>{
    
        static InputStream is = null;
    
    static JSONObject jObj = null;
    static String json = "";
    
    // constructor
    public JSONParser() {
    
    }
    @Override
    protected String doInBackground(String... params) {
    
    
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpPost = new HttpGet(url);
    
                HttpResponse getResponse = httpClient.execute(httpPost);
               final int statusCode = getResponse.getStatusLine().getStatusCode();
    
               if (statusCode != HttpStatus.SC_OK) { 
                  Log.w(getClass().getSimpleName(), 
                      "Error " + statusCode + " for URL " + url); 
                  return null;
               }
    
               HttpEntity getResponseEntity = getResponse.getEntity();
    
            //HttpResponse httpResponse = httpClient.execute(httpPost);
            //HttpEntity httpEntity = httpResponse.getEntity();
            is = getResponseEntity.getContent();            
    
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.d("IO", e.getMessage().toString());
            e.printStackTrace();
    
        }
    
        try {
            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();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
    
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
    
        // return JSON String
        return jObj;
    
    
    }
    protected void onPostExecute(String page)
    {   
        //onPostExecute
    }   
    }
    

    To call it (from main):

    mJSONParser = new JSONParser();
    mJSONParser.execute();
    

    Please make sure that you don't do any network access on UI Thread, instead do it in Async Task

    The reason why your application crashes on Android versions 3.0 and above, but works fine on Android 2.x is because since HoneyComb are much stricter about abuse against the UI Thread. For example, when an Android device running HoneyComb or above detects a network access on the UI thread, a NetworkOnMainThreadException will be thrown.

    See this

    链接地址: http://www.djcxy.com/p/29524.html

    上一篇: 造成者:android.os.NetworkOnMainThreadException

    下一篇: android.os.NetworkOnMainThreadException与android 4.2