获取JSON对象有时会使应用程序崩溃

时间:2012-10-31 13:10:56

标签: android

这是获取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()时,应用程序会停止响应(在大多数情况下,当我的互联网连接较弱时) 。我在网上搜索异步线程(或类似的东西),但我不知道如何在这段代码中实现。我有一种方法,用户可以在加载时看到进度条吗?

4 个答案:

答案 0 :(得分:0)

我认为主要的问题是你有三个独立的try / catch块,但是一旦你真正捕获到异常就不会停止处理。例如,您首先执行POST,如果失败,则尝试继续读取输出。相反,您应该在catch块中return;,以便停止处理。

AsyncTasks也很好,从4.0开始需要,但不是问题的解决方案。你也应该研究一下。

答案 1 :(得分: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);
  }

}

答案 2 :(得分:0)

我认为这是因为互联网连接。有时您的应用程序无法正确下载JSON内容,因此当它尝试解析时,它将进入错误状态并且您的应用程序崩溃是针对不正确的try-catch样式

答案 3 :(得分:0)

&#34;即使连接良好,asynchTask也无法解决无法访问网络的问题。 &#34;

你可以通过添加:

来修复它
httpclient.getConnectionManager().shutdown();

这将解决问题&#34;保持活力&#34;连接。