2013-11-14 79 views
0

我使用下面給出的解析器和一個示例Android 2.2。我的例子是工作,我沒有問題。當試圖在使用Android 4.3的項目中使用某個示例時。但我的解析器行有問題如何使用Json解析器android?

HttpResponse httpResponse = httpClient.execute(httpPost); 

我檢查了我的清單中的所有權限,所有這些權限都被使用。

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 
      Log.d("test url" , "le request est lancé") ; 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      HttpResponse httpResponse = httpClient.execute(httpPost); 
      Log.d("test url" , "la connection etablie"); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      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; 

    } 
} 

日誌是:

11-14 10:48:38.590: ERROR/AndroidRuntime(3801): FATAL EXCEPTION: main 
     java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.web.tab/fr.web.profilconfiguration.AndroidJSONParsingActivity}: android.os.NetworkOnMainThreadException 
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956) 
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 
     at android.app.ActivityThread.access$600(ActivityThread.java:123) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 
     at android.os.Handler.dispatchMessage(Handler.java:99) 
     at android.os.Looper.loop(Looper.java:137) 
     at android.app.ActivityThread.main(ActivityThread.java:4424) 
     at java.lang.reflect.Method.invokeNative(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:511) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
     at dalvik.system.NativeStart.main(Native Method) 
     Caused by: android.os.NetworkOnMainThreadException 
     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) 
     at java.net.InetAddress.lookupHostByName(InetAddress.java:391) 
     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242) 
     at java.net.InetAddress.getAllByName(InetAddress.java:220) 
     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 
     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 
     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 
     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 
     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 
     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 
     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 
     at fr.web.profilconfiguration.JSONParser.getJSONFromUrl(JSONParser.java:44) 
     at fr.web.profilconfiguration.AndroidJSONParsingActivity.onCreate(AndroidJSONParsingActivity.java:62) 
     at android.app.Activity.performCreate(Activity.java:4465) 
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920) 
+0

具有u使用網絡許可清單文件? – Ruban

+0

可能重複的[android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – laalto

回答

1

您正在主線程中執行網絡工作,以解決此錯誤的原因。 開發過程你使用這個,但不是生活的應用程序。

把這個代碼在onCreate方法的活動後的setContentView(佈局)

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

http://blog.vogella.com/2011/04/04/android-strictmode/。 StrictMode只能在開發過程中使用,而不能在實時應用程序中使用。 http://developer.android.com/reference/android/os/StrictMode.html。所以我想知道這是一個解決方案如何將代碼移動到線程 – Raghunandan

+1

這是一個非常糟糕的回答這個問題。 – cbrulak

2
Caused by: android.os.NetworkOnMainThreadException 

您正在運行的網絡realted在UI線程上運行。

HttpResponse httpResponse = httpClient.execute(httpPost); 

上述聲明必須在thread或的AsyncTask doInbackground。在UI線程上

http://developer.android.com/reference/android/os/AsyncTask.html

調用的AsyncTask new TheTask().execute()

class TheTask extends AsyncTask<Void ,Void, Void>{ 

     @Override 
     protected Void doInBackground(Void... params) { 
        JSONObject jobject =getJSONFromUrl(String url); 
      return null; 

     } 
    } 
+0

你能解釋更多嗎?在我的解析器中,params是什麼? – user2043602

+0

這是VAR args谷歌相同。那就是asynctask的doinbackground並將你的網絡相關代碼移到doinbackground。 – Raghunandan

+0

@ user2043602是什麼讓你認爲接受的答案是解決方案請看看這裏http://developer.android.com/reference/android/os/StrictMode.html – Raghunandan

1
public static JSONObject responseForSignin(final String uname,final String pwd) { 

     JSONObject jsonResponse = null; 
     HttpParams httpParameters = new BasicHttpParams(); 
     int connectionTimeout = 1000*12; 
     int socketTimeout = 1000*13; 
     HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout); 
     HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout); 
     // Create a new HttpClient and Post Header 
     HttpClient httpClient = new DefaultHttpClient(httpParameters); 
     HttpPost httpPost = new HttpPost("URL"); 
     httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); 

     try { 
      // Add your data 

      List<NameValuePair> signinDetails = new ArrayList<NameValuePair>(); 
      signinDetails.add(new BasicNameValuePair("name", uname)); 
         signinDetails.add(new BasicNameValuePair("pwd", 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("responseCode", String.valueOf("response code"+responseCode)); 
       HttpEntity entity = httpResponse.getEntity(); 
       Log.e("entity", String.valueOf(entity)); 
       if (entity != null) { 

        if (entity != null) { 

         String responseBody = EntityUtils.toString(entity); 
         JSONTokener jsonTokener = new JSONTokener(responseBody); 
         jsonResponse = new JSONObject(jsonTokener); 
         JSONObject response = jsonResponse.getJSONObject("response"); 
         // Getting String inside response object 
         String status = response.getString("status"); 
         String message = response.getString("message"); 

        } 
       } // if (entity != null) end 
     } 

     catch (SocketException seExp) 
     { 

     } 
     catch (ConnectTimeoutException cteExp) 
     { 
     // TODO Auto-generated catch block 

     } 
     catch (ClientProtocolException cpeExp) { 
      // TODO Auto-generated catch block 
     } 

      catch (UnknownHostException e) { 
       // TODO Auto-generated catch block 

       e.printStackTrace(); 
      } 
     catch (Exception allExp) { 
      // TODO Auto-generated catch block 
     }  
     return jsonResponse; 
    } 

試試這個

public class RequestLogInFromServer extends AsyncTask<Object, Object, Object> 
    { 

     private ProgressDialog progressDialog; 


     @Override 
     protected Object doInBackground(Object... params) 
     { 

        try { 

         JSONObject subscriptionResponse = CommonJsonParser.responseForSignin(uname, pwd).getJSONObject("response"); 

         if (!(subscriptionResponse.equals(null))||!(subscriptionResponse.equals(""))) {      


         } 


        } 



        catch (NullPointerException e) { 
         // TODO Auto-generated catch block 


        } 


        catch (JSONException e) { 
         // TODO Auto-generated catch block 
        } 


        catch (Exception e) { 
         // TODO Auto-generated catch block 
        } 

      return null; 

     } 


     @Override 
     protected void onPostExecute(Object result) 
     {  
      if(progressDialog!=null){ 
      progressDialog.dismiss(); 
      }  

      super.onPostExecute(result); 
     } 

     @Override 
     protected void onPreExecute() { 

      progressDialog = ProgressDialog.show(SignInActivity.this, "", "Please wait"); 
      super.onPreExecute(); 
     } 

    } 

使用AsyncTask.any服務器請求,或需要很長的時間應在後臺任務被寫

4

不使用主線程中的網絡活動。僅針對應用程序引發此異常定位到Honeycomb SDK或更高版本。在單獨的線程中執行所有與網絡有關的任務。你的問題將得到解決。