2014-01-28 137 views
-1

我試圖讀取服務器的JSON但not'm越來越閱讀JSON在Android

public JSONObject getJSON(){ 
    JSONObject jsonObject = null; 
    try{ 
    // Create a new HTTP Client 
    DefaultHttpClient defaultClient = new DefaultHttpClient(); 
    // Setup the get request 
    HttpGet httpGetRequest = new HttpGet("URL"); 

    // Execute the request in the client 
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest); 
    // Grab the response 
    BufferedReader reader = new BufferedReader(new       
     InputStreamReader(httpResponse.getEntity(). 
     getContent(), "UTF-8")); 
    String json = reader.readLine(); 

    // Instantiate a JSON object from the request response 
    jsonObject = new JSONObject(json); 

} catch(Exception e){ 
    // In your production code handle any errors and catch the individual exceptions 
    e.printStackTrace(); 
} 
return jsonObject; 

}
例外:

android.os.NetworkOnMainThreadException 

我使用標籤許可使用互聯網的XML Android

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.INTERNET" /> 
+0

http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – Raghunandan

回答

0

嘗試使用AsyncTask做到這一點,因爲網絡mustnt be on主線程