我想向我的arrayadapter
添加一个新项目,然后使其在我的视图中呈现。在网上进行挖掘后,我注意到ArrayAdapter类保留了自己的arraylist
版本,如下所述:Android ListView not refreshing after notifyDataSetChanged。
这里是我的代码:
The add new item code:
public void addRecordSet(View view) {
RecordStats recordStats = new RecordStats();
recordStats.RecordID = mRecord.id;
long recordStatId = mDatabaseHelper.addRecordStats(recordStats);
recordStats.ID = (int) recordStatId;
recordStatsList.add(recordStats);
mAdapter.swapRecordFormList(recordStatsList);
}
The arrayadapter code:
public void swapRecordFormList(ArrayList<RecordStats> recordStatsList) {
mRecordStatsList = recordStatsList;
notifyDataSetChanged();
}
但是,我收到此错误:
Process: com.example.andyxu.enzo3, PID: 19289
java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.get(ArrayList.java:437)
有什么想法吗?
编辑:
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View recordForm = convertView;
if (recordForm == null) {
recordForm = LayoutInflater.from(mContext).inflate(R.layout.custom_record_form, parent, false);
}
RecordStats currentRecord = mRecordStatsList.get(position);
EditText reps = (EditText) recordForm.findViewById(R.id.reps);
if (currentRecord.Reps > 0) {
reps.setText(String.valueOf(currentRecord.Reps));
}
EditText weight = (EditText) recordForm.findViewById(R.id.weight);
if (currentRecord.Weight > 0) {
weight.setText(String.valueOf(currentRecord.Weight));
}
return recordForm;
}
答案 0 :(得分:1)
ArrayAdapter
可以由您提供的实时列表对象支持。 (因此,您引用的链接与您的情况不太相关)。使用ArrayAdapter
,您需要做的就是在后备列表对象上调用add
,然后调用notifyDataSetChanged
。
List<String> list = new ArrayList<>();
ArrayAdapter<String> adatper = new ArrayAdapter<String>(this, android.R.layout.layout, list);
listView.setAdapter(adapter);
list.add("Another item");
adapter.notifyDataSetChanged();