2013-05-08 12 views
20

Qui sto usando questo codice di caricamento Json. È un lavoro bene con Android 2.2, ma quando sto usando Android 4.2 getta android.os.NetworkOnMainThreadException eccezione per favore mi dia soluzioneandroid.os.NetworkOnMainThreadException con 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; 

} 

}

Sono anche utilizzando API di Google.

+0

questione è è stato risposto qui: http://stackoverflow.com/questions/5150637/networkonmainthreade xception –

+0

http://stackoverflow.com/a/12615724/1168654 –

risposta

73

Scrivi sotto il codice nel file MainActivity dopo 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); 
} 

E sotto istruzione di importazione nel file java.

import android.os.StrictMode; 
+38

non è il modo corretto per disattivare StrictMode. Il modo corretto è di chiamare le operazioni di rete in AsyncTask invece di spegnere –

+0

Come @SankarV dice che dovrebbe essere fatto usando un AsyncTask invece di disattivare strictmode. –

+0

Questo non è raccomandato. AsyncTask è un modo migliore per farlo. –

6

Si prega di assicurarsi che non si fa alcun accesso alla rete sulla UI thread, invece farlo in Async Task

Il motivo per cui i tuoi applicazione si blocca su versioni di Android 3.0 e superiori, ma funziona bene su Android 2.x perché HoneyComb è molto più severo in merito all'abuso contro il thread UI. Ad esempio, quando un dispositivo Android con HoneyComb o versioni successive rileva un accesso di rete sul thread dell'interfaccia utente, verrà generata una NetworkOnMainThreadException.

Vedi this

+0

invece di HoneyComb e Ice Cream Sandwich dirò Da HoneyComb. Infatti JB ha la stessa politica – Blackbelt

1

android.os.NetworkOnMainThreadException si verifica quando si tenta di accedere alla rete sul thread principale (main È l'esecuzione di attività). Per evitare ciò, è necessario creare un thread separato o un'implementazione AsyncTask o Runnable per eseguire il caricamento dei dati JSON. Poiché HoneyComb non è possibile eseguire ulteriormente l'attività di rete sul thread principale. Here è l'implementazione utilizzando AsyncTask per l'esecuzione di un compito di rete

1

Usa StrictMode Qualcosa di simile a questo: -

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

     StrictMode.setThreadPolicy(policy); 
     } 
+2

non è il modo corretto per disattivare StrictMode. Il modo corretto è di chiamare le operazioni di rete in AsyncTask invece di spegnersi. è fornito il controllo solo per lo spegnimento? –

+0

possiamo usare asynkTask anche se per me funziona –

+0

ya funzionerà ma non nel modo migliore. hanno fornito il controllo per garantire che lo sviluppatore chiami le operazioni di rete in thread separati e non per lo spegnimento. –

13

Questo è il modo corretto:

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

chiamarlo (da principale):

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

lo hai provato? Non funziona cos'è l'url? return obj non è accessibile al di fuori del loop –

Problemi correlati