我把JSON對象從我的服務器上的PHP腳本生成,然後使用延遲加載的圖像解析爲列表視圖。問題在於json的加載速度會相對較快,或者會根據服務器上的響應而暫停一兩秒鐘,這可能令人沮喪。當我第一次打開應用程序的竅門是espcially煩人,因爲它會在一個黑色屏幕,直到對象已經加載掛,然後當我更新的應用程序具有相同的,但至少認爲已經加載列表。這裏是我的代碼來獲取JSON:設置異步任務加載JSON轉換成一個ListView
public void getJson(String selection, String url) {
JSONObject json = null;
String formatedcat = selection.toLowerCase();
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
json = JSONfunctions
.getJSONfromURL(url);
try {
//the array title that you parse
JSONArray category = json.getJSONArray(formatedcat);
for (int i = 0; i < category.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = category.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name",
c.getString("title"));
//map.put("text",c.getString("title"));
map.put("ts",c.getString("run_date"));
map.put("image","http:"+c.getString("url"));
mylist.add(map);
}
} catch (JSONException e) {
}
ListAdapter adapter = new JsonAdapter(this, mylist, R.layout.list,
new String[] { "name", "text", "ts"}, new int[] { R.id.item_title,
R.id.item_subtitle, R.id.timestamp});
setListAdapter(adapter);
}
適配器代碼:
public class JsonAdapter extends SimpleAdapter {
public ImageManager imageManager;
public ListActivity context;
public ArrayList<HashMap<String,String>> list;
public String[] fieldNames;
public int[] fieldTargetIds;
public JsonAdapter(ListActivity c,
ArrayList<HashMap<String, String>> mylist,
int textViewResourceId,
String[] fieldNames,
int[] fieldTargetIds) {
super(c, mylist, textViewResourceId, fieldNames, fieldTargetIds);
this.context = c;
this.list = mylist;
this.fieldNames = fieldNames;
this.fieldTargetIds = fieldTargetIds;
this.imageManager = new ImageManager(context.getApplicationContext());
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = vi.inflate(R.layout.list, null);
}
//super.getView(position, convertView, parent);
ImageView imgView = (ImageView) row.findViewById(R.id.doodlepic);
try {
String url = list.get(position).get("image");
imgView.setTag(url);
imageManager.displayImage(url, context, imgView);
} catch (Exception e) {
}
for (int i=0; i<fieldNames.length; i++) {
TextView tv = (TextView) row.findViewById(fieldTargetIds[i]);
tv.setText(list.get(position).get(fieldNames[i]));
}
return row;
}
}
我怎麼能執行一個異步任務,以顯示進度對話框,而正在生成並下載了JSON對象?我試過使用線程和異步任務,但我無法弄清楚如何將代碼拆分成適當的部分。
你應該總是創建一個單獨的線程來處理JSON取。這樣你的應用程序就不會掛起。不完全是你想要的,但是當你的線程獲取JSON時,你可以顯示一個'Loading ...'文本作爲彈出窗口,並在獲取JSON後自動解除。 – Urban 2012-02-19 22:09:46
任何想法如何我可以使我上面列出的Json函數的線程? – Nick 2012-02-19 22:10:53
這可能有所幫助:http://stackoverflow.com/a/3027900/595947 – Urban 2012-02-19 22:20:19