這是我得到的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()應用程序停止反應(在大多數情況下,當我有一個弱的互聯網連接)。我搜索網絡異步線程(或類似的東西),但我不知道如何在此代碼中實現。我有一種方式,用戶可以在加載時看到進度條嗎?
你不應該在UI線程上做網絡請求。 搜索AsyncTask。 –