我正在开发 android 中的应用程序。我有这段代码,我尝试将它与 volley 一起使用,以便我可以加载 json 并使用 json 将项目添加到列表中,但我总是做错了......
package com.hmkcode.android;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.ListActivity;
public class MainActivity extends ListActivity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// 1. pass context and data to the custom adapter
MyAdapter adapter = new MyAdapter(this, generateData());
//2. setListAdapter
setListAdapter(adapter);
}
private ArrayList<Item> generateData(){
ArrayList<Item> items = new ArrayList<Item>();
items.add(new Item("Item 1","First Item on the list"));
items.add(new Item("Item 2","Second Item on the list"));
items.add(new Item("Item 3","Third Item on the list"));
return items;
}
}
我试图像这样实现它,但是我在 onResponse 中设置的静态项目没有显示,而且当我尝试点击这些项目时,应用程序最终崩溃
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// 1. pass context and data to the custom adapter
MyAdapter adapter = new MyAdapter(this, generateData());
//2. setListAdapter
setListAdapter(adapter);
}
private ArrayList<Item> generateData(){
ArrayList<Item> items = new ArrayList<Item>();
items.add(new Item("Item 1","First Item on the list"));
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://echo.jsontest.com/just/test/values/two";
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//my loop here
items.add(new Item("Item 1","this is just a sample "));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
queue.add(jsObjRequest);
return items;
}
编辑:
11-09 13:25:00.465:E/AndroidRuntime(10699): java.lang.IllegalStateException:
The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131230722, class android.widget.ListView) with Adapter(class android.janime.MyAdapter)]
当我在执行 onResponse 后单击列表中的一项时,应用程序崩溃。“确保适配器的内容不是从后台线程修改的,而只是从 UI 线程修改的。”