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