我想使用ArrayList动态地将数据保存在recyclerview中,但是我遇到了问题。
每次我在回收器视图中添加数据时,它都会替换之前的数据,并仅显示我输入的最后一个数据。
我正在使用SharedPreference将该值传递给这样的下一个活动
let singleData = self.arrayData[0] as! [String:Any]
print(singleData["id_ser_reg"])
print(singleData["n_ser_reg"])
这是我在ArrayList中添加数据的活动;
Results.java
builder.setNeutralButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences sp = getSharedPreferences(mypreference,0);
SharedPreferences.Editor editor = sp.edit();
size = sp.getInt("size",size);
size = size+1;
editor.putString("name"+size , scanResult);
editor.putInt("size" , size);
editor.commit();
finish();
}
});
这是recyclerview的适配器
ResultAdapter.java
ArrayList<String> data = new ArrayList<>();
pref = getSharedPreferences(mypreference,MODE_PRIVATE);
int size = pref.getInt("size",0);
String scanResult = pref.getString("name"+size,"");
data.add(scanResult);
listView_result = findViewById(R.id.listResult);
LinearLayoutManager layoutManager = new
LinearLayoutManager(getApplicationContext());
listView_result.setLayoutManager(layoutManager);
ResultAdapter adapter = new ResultAdapter(Results.this, data);
listView_result.setAdapter(adapter);
答案 0 :(得分:0)
int size = pref.getInt("size",0);
String scanResult = pref.getString("name"+size,"");
data.add(scanResult);
以上应该是
int size = pref.getInt("size",0);
for (int i = 0; i < size; ++i) {
String scanResult = pref.getString("name"+i,"");
data.add(scanResult);
}