我把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