无法将JSON中的新数据添加到Android中Listview的适配器
我是Android的绝对初学者。我正在学习如何使用截取并将来自截取请求响应的数据绑定到listview。一切正常。但是当我将它绑定到Listview时。这是投掷错误。我的代码有什么问题?这样做正确吗 我的活动课无法将JSON中的新数据添加到Android中Listview的适配器,android,listview,android-volley,Android,Listview,Android Volley,我是Android的绝对初学者。我正在学习如何使用截取并将来自截取请求响应的数据绑定到listview。一切正常。但是当我将它绑定到Listview时。这是投掷错误。我的代码有什么问题?这样做正确吗 我的活动课 public class VolleyActivity extends Activity{ private int lastSawFirstListItem; private int itemLoadedOn; private ArrayAdapter adapt
public class VolleyActivity extends Activity{
private int lastSawFirstListItem;
private int itemLoadedOn;
private ArrayAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.volley_main);
Button getBtn = (Button)findViewById(R.id.btn_get_request);
getBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
ListView listView = (ListView)findViewById(R.id.volleyListView);
adapter = new CustomAdapter(this,new Entity[0]);
listView.setAdapter(adapter);
String url = "http://api.androidhive.info/feed/feed.json";
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
List<Entity> items = new ArrayList<Entity>();
try{
JSONArray jsonArray = jsonObject.getJSONArray("feed");
for(int i=0;i<jsonArray.length();i++)
{
JSONObject item = jsonArray.getJSONObject(i);
Entity en = new Entity();
en.setId(item.getInt("id"));
en.setName(item.getString("name"));
en.setUrl(item.getString("url"));
items.add(en);
}
adapter.addAll(items);
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(),"Success",Toast.LENGTH_SHORT).show();
}
catch (JSONException e)
{
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
Volley.newRequestQueue(getBaseContext()).add(jsonRequest);
}
}
这是将截击与Listview和绑定数据一起使用的正确方法吗?如何修复此错误
然后,我在自定义适配器中从Entity[]更改为ArrayList
。这仍然是一个错误
我的带有ArrayList的新自定义适配器类
public class CustomAdapter extends ArrayAdapter<Entity> {
private final Context context;
private final ArrayList<Entity> values;
public CustomAdapter(Context context,ArrayList<Entity> values)
{
super(context,-1,values);
this.context = context;
this.values = values;
}
@Override
public View getView(int position,View convertView,ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_row,parent,false);
TextView id_text = (TextView)rowView.findViewById(R.id.row_id);
TextView name_text = (TextView)rowView.findViewById(R.id.row_name);
TextView url_text = (TextView)rowView.findViewById(R.id.row_url);
id_text.setText(values.get(position).getId());
name_text.setText(values.get(position).getName());
url_text.setText(values.get(position).getUrl());
return rowView;
}
}
01-22 05:09:54.770 1895-1895/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa6219908)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: FATAL EXCEPTION: main
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: android.content.res.Resources$NotFoundException: String resource ID #0x1
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.content.res.Resources.getText(Resources.java:230)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.TextView.setText(TextView.java:3769)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at com.example.newfeeds.newfeeds.CustomAdapter.getView(CustomAdapter.java:36)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.AbsListView.obtainView(AbsListView.java:2159)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.ListView.makeAndAddView(ListView.java:1831)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.ListView.fillDown(ListView.java:674)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.ListView.fillFromTop(ListView.java:735)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.ListView.layoutChildren(ListView.java:1638)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.AbsListView.onLayout(AbsListView.java:1994)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.View.layout(View.java:14008)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.ViewGroup.layout(ViewGroup.java:4373)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1663)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1521)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.View.layout(View.java:14008)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.ViewGroup.layout(ViewGroup.java:4373)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.View.layout(View.java:14008)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.ViewGroup.layout(ViewGroup.java:4373)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1663)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1521)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.View.layout(View.java:14008)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.ViewGroup.layout(ViewGroup.java:4373)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.View.layout(View.java:14008)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.ViewGroup.layout(ViewGroup.java:4373)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1892)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1711)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.Choreographer.doCallbacks(Choreographer.java:562)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.Choreographer.doFrame(Choreographer.java:532)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:725)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:92)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5041)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-22 05:09:54.774 1895-1895/? E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
01-22 05:09:54.778 477-489/? W/ActivityManager: Force finishing activity com.example.newfeeds.newfeeds/.VolleyActivity
01-22 05:09:54.894 477-489/? D/dalvikvm: GC_FOR_ALLOC freed 179K, 33% free 9817K/14460K, paused 15ms, total 15ms
01-22 05:09:55.398 477-490/? W/ActivityManager: Activity pause timeout for ActivityRecord{5334f1a0 u0 com.example.newfeeds.newfeeds/.VolleyActivity}
好的,如果我理解正确的话,您使用的是
Entity[]values
,这是一个普通数组,您必须在初始化它时定义它的大小
问题是,使用这个普通数组时,它不能在移动中进行扩展或收缩(我的意思是你不能减少或添加更多项)。所以它的大小和初始化时一样
在您的活动中,您提供的是一个ArrayList
对象,可以在移动中添加或删除项目
这就是你们在这里面临的冲突
您需要做的是在Customadapter
中有一个ArrayList
实例,类似这样
private final Context context;
private final ArrayList<Entity> values;
public CustomAdapter(Context context,ArrayList<Entity> values;
{
super(context,-1,values);
this.context = context;
this.values = values;
}
并调用此方法notifyDataSetChanged()
,因为您具有使用观察者模式的优势
adapter.notifyDataSetChanged();
您还可以使用JSON
on查看listview
population上的一些示例
您必须更像OOP那样思考,创建一个模型类,其实例将为您保存数据
public class Entity {
private String id;
private String name;
private String url;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
更新,
因为有很多困惑,试试这个
公共类ListVewTestThreeActivity扩展了AppCompatActivity{
私有列表视图列表视图;
私有ArrayList实体;
私有MyAdapter MyAdapter;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u list\u vew\u test\u three);
工具栏工具栏=(工具栏)findViewById(R.id.my\u自定义工具栏);
设置支持操作栏(工具栏);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
初始化();
}
private void initializeUI(){
listView=(listView)findViewById(R.id.ListVewtTestThreeActivity_listView);
实体=新的ArrayList();
myAdapter=新的myAdapter(getApplicationContext(),R.layout.simple\u list\u item\u 1,实体);
setAdapter(myAdapter);
新建下载JSON().execute();
}
私有类下载JSON扩展异步任务{
私有ArrayList实体;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
tempEntities=newArrayList();
}
@凌驾
受保护的Void doInBackground(Void…参数){
试一试{
URL=新URL(“http://api.androidhive.info/feed/feed.json");
HttpURLConnection HttpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.connect();
字符串结果=IOUtils.toString(httpURLConnection.getInputStream());
System.out.println(“+”结果);
JSONObject JSONObject=新JSONObject(结果);
JSONArray JSONArray=jsonObject.getJSONArray(“提要”);
for(int i=0;ivalues.addAll(items);
adapter.notifyDataSetChanged();
public class Entity {
private String id;
private String name;
private String url;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
public class ListVewTestThreeActivity extends AppCompatActivity {
private ListView listView;
private ArrayList<Entity> entities;
private MyAdapter myAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_vew_test_three);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_custom_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
initializeUI();
}
private void initializeUI() {
listView = (ListView) findViewById(R.id.ListVewTestThreeActivity_listView);
entities = new ArrayList<>();
myAdapter = new MyAdapter(getApplicationContext(), R.layout.simple_list_item_1, entities);
listView.setAdapter(myAdapter);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
private ArrayList<Entity> tempEntities;
@Override
protected void onPreExecute() {
super.onPreExecute();
tempEntities = new ArrayList<>();
}
@Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://api.androidhive.info/feed/feed.json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
String result = IOUtils.toString(httpURLConnection.getInputStream());
System.out.println("" + result);
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("feed");
for (int i = 0; i < jsonArray.length(); i++) {
Entity entity = new Entity();
entity.setId(jsonArray.getJSONObject(i).getString("id"));
entity.setName(jsonArray.getJSONObject(i).getString("name"));
entity.setUrl(jsonArray.getJSONObject(i).getString("image"));
System.out.println(""+entity.getName());
tempEntities.add(entity);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (tempEntities != null) {
entities.addAll(tempEntities);
System.out.println("Size: "+entities.size());
myAdapter.notifyDataSetChanged();
}
}
}
private class MyAdapter extends ArrayAdapter {
private ArrayList<Entity> a_productInfos;
private Context a_context;
private LayoutInflater a_layoutInflater;
public MyAdapter(Context context, int resource, ArrayList<Entity> a_productInfos) {
super(context, resource, a_productInfos);
this.a_productInfos = a_productInfos;
this.a_context = context;
a_layoutInflater = LayoutInflater.from(this.a_context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
row = a_layoutInflater.inflate(R.layout.single_item_listview_test_three, parent, false);
holder = new ViewHolder();
holder.id = (TextView) row.findViewById(R.id.ListVewTestThreeActivity_id_textView);
holder.name = (TextView) row.findViewById(R.id.ListVewTestThreeActivity_name_textView);
holder.url = (TextView) row.findViewById(R.id.ListVewTestThreeActivity_url_textView);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Entity productInfo = a_productInfos.get(position);
holder.id.setText("" + productInfo.getId());
holder.name.setText("" + productInfo.getName());
holder.url.setText("" + productInfo.getUrl());
return row;
}
class ViewHolder {
TextView id;
TextView name;
TextView url;
}
@Override
public int getCount() {
return super.getCount();
}
}
public class Entity {
private String id;
private String name;
private String url;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
public class VolleyActivity extends Activity{
private int lastSawFirstListItem;
private int itemLoadedOn;
private ArrayAdapter adapter;
private List<Entity> items;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.volley_main);
Button getBtn = (Button)findViewById(R.id.btn_get_request);
getBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
items = new ArrayList<Entity>();
ListView listView = (ListView)findViewById(R.id.volleyListView);
adapter = new CustomAdapter(this, items);
listView.setAdapter(adapter);
String url = "http://api.androidhive.info/feed/feed.json";
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
List<Entity> items = new ArrayList<Entity>();
try{
JSONArray jsonArray = jsonObject.getJSONArray("feed");
for(int i=0;i<jsonArray.length();i++)
{
JSONObject item = jsonArray.getJSONObject(i);
Entity en = new Entity();
en.setId(item.getInt("id"));
en.setName(item.getString("name"));
en.setUrl(item.getString("url"));
items.add(en);
}
adapter.addAll(items);
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(),"Success",Toast.LENGTH_SHORT).show();
}
catch (JSONException e)
{
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
Volley.newRequestQueue(getBaseContext()).add(jsonRequest);
}
}
public class CustomAdapter extends ArrayAdapter<Entity> {
private final Context context;
private List<Entity> values;
public CustomAdapter(Context context,List<Entity> values){
super(context,-1,values);
this.context = context;
this.values = values;
}
@Override
public View getView(int position,View convertView,ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_row,parent,false);
TextView id_text = (TextView)rowView.findViewById(R.id.row_id);
TextView name_text = (TextView)rowView.findViewById(R.id.row_name);
TextView url_text = (TextView)rowView.findViewById(R.id.row_url);
id_text.setText(String.valueOf(values.get(position).getId()));
name_text.setText(values.get(position).getName());
url_text.setText(values.get(position).getUrl());
return rowView;
}
}
id_text.setText(String.valueOf(values[position].getId()))
String.valueOf(values.get(position).getId())