2012-10-31 45 views
0

這是我得到的JSON陣列碼:獲取JSON對象有時會崩潰的應用程序

public void download_vse_igralce(View view) 
{ 
    mylist.clear(); //sem dal v oklepaje 
    String result = ""; 
    //the year data to send 
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("year","1980")); 
    InputStream is = null; 
    //http post 
    try{ 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://gregor-apps.com/ubs/pokazi_vse_igralce.php"); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 
    }catch(Exception e){ 
      Log.e("log_tag", "Error in http connection "+e.toString()); 
    } 

    //convert response to string 
    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(); 

      result=sb.toString(); 
    }catch(Exception e){ 

      Log.e("log_tag", "Error converting result "+e.toString()); 
    } 

    //parse json data 
    try{ 
     { 
      JSONArray jArray = new JSONArray(result); 
      for(int i=0;i<jArray.length();i++){ 
        json_data = jArray.getJSONObject(i); 


        Log.i("log_tag","id: "+json_data.getInt("id")+ 
          ", ime: "+json_data.getString("ime")+ 
          ", priimek: "+json_data.getString("priimek")+ 
          ", pozicija: "+json_data.getString("pozicija") 
          ); 

          HashMap<String, String> map = new HashMap<String, String>(); 

        map.put("id", json_data.getString("id"));      
        map.put("firstname", json_data.getString("ime"));      
        map.put("lastname", json_data.getString("priimek")); 
        map.put("position", json_data.getString("pozicija")); 
        map.put("height", json_data.getString("height")); 
        map.put("weight", json_data.getString("weight")); 
        map.put("hometown", json_data.getString("hometown")); 
        map.put("birthdate", json_data.getString("birthdate"));  
        map.put("jersey", json_data.getString("number")); 
        map.put("picture", json_data.getString("slika")); 
        mylist.add(map); 

      } 
      downloadani_igralci=1; 


    } 

    }catch(JSONException e){ 
     downloadani_igralci=0; 
      Log.e("log_tag", "Error parsing data "+e.toString()); 
    } 
    settings(view); 
} 

一般這種代碼的偉大工程,因爲我希望它返回MYLIST。但不時,當我調用我的函數download_vse_igralce()應用程序停止反應(在大多數情況下,當我有一個弱的互聯網連接)。我搜索網絡異步線程(或類似的東西),但我不知道如何在此代碼中實現。我有一種方式,用戶可以在加載時看到進度條嗎?

+2

你不應該在UI線程上做網絡請求。 搜索AsyncTask。 –

回答

0

是這樣的:

public void download_vse_igralce(View view){ 
    mylist.clear(); 
    JSONParserTask task = new JSONParserTask(); 
    task.execute(); 
} 

private class JSONParserTask extends AsyncTask<Void, Void, Void> { 

    protected Void doInBackground(Void... ignoredParams) { 
    String result = ""; 
//the year data to send 
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
nameValuePairs.add(new BasicNameValuePair("year","1980")); 
InputStream is = null; 
//http post 
try{ 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://gregor-apps.com/ubs/pokazi_vse_igralce.php"); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 
}catch(Exception e){ 
     Log.e("log_tag", "Error in http connection "+e.toString()); 
} 

//convert response to string 
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(); 

     result=sb.toString(); 
}catch(Exception e){ 

     Log.e("log_tag", "Error converting result "+e.toString()); 
} 

//parse json data 
try{ 
    { 
     JSONArray jArray = new JSONArray(result); 
     for(int i=0;i<jArray.length();i++){ 
       json_data = jArray.getJSONObject(i); 


       Log.i("log_tag","id: "+json_data.getInt("id")+ 
         ", ime: "+json_data.getString("ime")+ 
         ", priimek: "+json_data.getString("priimek")+ 
         ", pozicija: "+json_data.getString("pozicija") 
         ); 

         HashMap<String, String> map = new HashMap<String, String>(); 

       map.put("id", json_data.getString("id"));      
       map.put("firstname", json_data.getString("ime"));      
       map.put("lastname", json_data.getString("priimek")); 
       map.put("position", json_data.getString("pozicija")); 
       map.put("height", json_data.getString("height")); 
       map.put("weight", json_data.getString("weight")); 
       map.put("hometown", json_data.getString("hometown")); 
       map.put("birthdate", json_data.getString("birthdate"));  
       map.put("jersey", json_data.getString("number")); 
       map.put("picture", json_data.getString("slika")); 
       mylist.add(map); 

     } 
     downloadani_igralci=1; 


} 

}catch(JSONException e){ 
    downloadani_igralci=0; 
     Log.e("log_tag", "Error parsing data "+e.toString()); 
} 
    } 

    protected void onPostExecute(Void array) { 
    settings(view); 
    } 

} 
+0

asynchTask並不能解決無法訪問網絡的問題,甚至如果連接良好。我不時得到異常訪問着名的谷歌的GeoCoder服務 – injecteer

+0

這似乎工作...謝謝。 – Gregor

0

我相信主要的問題是你有三個單獨的try/catch塊,但是一旦你真的發現異常,你就不會停止處理。例如,你首先做一個POST,如果失敗了,你就嘗試讀取輸出。相反,您應該在catch塊中使用return;,以便停止處理。

AsyncTasks也很好,從4.0開始需要,但不是解決問題的辦法。你也應該考慮一下。

+0

Try/catch塊實際上並不重要。 UI線程上的長操作(網絡請求)是導致應用程序停止響應的原因。 –

+0

AsyncTask從不需要。從UI線程執行網絡操作需要從3.0開始。 – HandlerExploit

+0

三個分離的try/catch塊有什麼區別嗎?我認爲它只能防止應用程序崩潰(例如,如果第一個不起作用,那麼其他兩個都不起作用 - 但它不會使應用程序崩潰)。謝謝你對我的問題做出如此快速的反應 - 我對這個新東西很陌生... – Gregor

0

我認爲這將是因爲互聯網連接。有時你的應用程序無法正確下載JSON內容,所以當它試圖解析時,它會進入錯誤狀態,並且應用程序崩潰是因爲試圖捕獲的不當樣式。

0

「asynchTask無法解決問題網絡不可達不過,即使連接好「

您可以通過添加修復:

httpclient.getConnectionManager().shutdown(); 

這將解決這個問題的‘保持活動’的連接。

相關問題