2013-05-08 49 views
20

在这里,我使用此代码加载Json。它做工精细的Android 2.2,但是当我使用的Android 4.2,它抛出android.os.NetworkOnMainThreadException例外,请给我解决android.os.NetworkOnMainThreadException与android 4.2

public class JSONParser { 

    static InputStream is = null; 

static JSONObject jObj = null; 
static String json = ""; 

// constructor 
public JSONParser() { 

} 

public JSONObject getJSONFromUrl(String url) { 

    // 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; 

} 

}

我也使用谷歌API。

+0

问题有已在这里回答:http://stackoverflow.com/questions/5150637/networkonmainthreade xception – 2013-05-08 11:35:21

+0

http://stackoverflow.com/a/12615724/1168654 – 2013-05-08 11:38:13

回答

73

在setContentView(R.layout.activity_main)之后将代码写入您的MainActivity文件中;

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

和下面的import语句放到你的java文件中。

import android.os.StrictMode; 
+38

它不是关闭StrictMode的正确方法。正确的方法是在AsyncTask中调用网络操作而不是关闭 – 2013-05-08 11:40:26

+0

由于@SankarV表示应该使用AsyncTask来完成,而不是关闭strictmode。 – 2013-10-09 08:29:48

+0

这不建议。 AsyncTask是一个更好的方法来做到这一点。 – 2015-08-25 05:31:09

6

请确保你不这样做的UI线程任何网络访问,而不是做在Async Task

之所以在Android 3.0及以上版本,您的应用程序崩溃,但能正常工作在Android 2.X是因为HoneyComb对UI线程的滥用要严格得多。例如,当运行HoneyComb或更高版本的Android设备检测到UI线程上的网络访问时,将引发NetworkOnMainThreadException。

见当您尝试访问网络上的主线程(您的主要活动执行)发生this

+0

而不是HoneyComb和冰淇淋三明治我会说自从HoneyComb。实际上JB有相同的策略 – Blackbelt 2013-05-08 11:42:30

1

android.os.NetworkOnMainThreadException。为了避免这种情况,您必须创建一个单独的线程或AsyncTaskRunnable实现来执行您的JSON数据加载。由于HoneyComb不能在主线程上进一步执行网络任务。 Here是使用AsyncTask执行网络任务的实现

1

使用StrictMode事情是这样的: -

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

     StrictMode.setThreadPolicy(policy); 
     } 
+2

这不是关闭StrictMode的正确方法。正确的方法是在AsyncTask中调用网络操作而不是关闭。他们提供的支票只是为了关闭? – 2013-05-08 11:42:34

+0

我们也可以使用asynkTask,但对我来说,它的工作 – 2013-05-08 11:45:55

+0

雅它会工作,但不是最好的方法。他们提供了检查以确保开发者在单独的线程中调用网络操作,而不是简单地关闭。 – 2013-05-08 11:51:13

13

这是正确的做法:

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

要调用它(从主):

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

你甚至测试过吗?不起作用的是什么网址?返回obj不能在循环外部访问 – 2014-04-03 09:32:53

相关问题