Android arrayList 的整个项目被最后一个替换

Android arrayList whole items is replaced by last one

我使用以下代码从 table 中获取行。当我第一次遍历组时,第一个项目被添加到数组列表中,它显示了确切的值。第二次迭代后,第一个对象被第二个对象替换,现在有两个重复元素。这背后的原因可能是什么?

c.moveToFirst();
        ArrayList<BaseModel> userShares = new ArrayList<BaseModel>();
        for (int count=0;count<recordCount;count++) {
            UserShareModel userShareModel = (UserShareModel) model;
            userShareModel.setUserId(c.getString(c.getColumnIndexOrThrow("userid")));
            userShareModel.setType(c.getInt(c.getColumnIndexOrThrow("type")));
            userShareModel.setKeyUserShare(c.getString(c.getColumnIndexOrThrow("key_user_share")));
            userShareModel.setSecretSeed(c.getString(c.getColumnIndexOrThrow("secret_seed")));
            userShareModel.setValueUserShare(c.getString(c.getColumnIndexOrThrow("value_user_share")));
            userShareModel.setCreatedAt(c.getString(c.getColumnIndexOrThrow("created_at")));
            String updatedAt = c.getString(c.getColumnIndexOrThrow("updated_at"));
            if (updatedAt != null) {
                userShareModel.setUpdatedAt(updatedAt);
            }
            userShares.add(userShareModel);
            c.moveToNext();
        }

我通常是这样做的:

    if (cursor.moveToFirst()) {
        do {
            UserShareModel userShareModel = (userShareModel.setUserId(c.getString(0)), .... usw //probably working with getColumnIndexOrThrow("userid")));


            userShares.add(userShareModel);
        } while (cursor.moveToNext());
    }

您正在使用相同的 BaseModel model 实例在每次迭代中填充数据。因此,您所有的数组列表引用都指向同一个对象(具有最后更新的数据的同一个对象)。

您应该在每个循环迭代中创建一个 BaseModel model 的新实例。

for (int count=0;count<recordCount;count++) {
UserShareModel userShareModel = new UserShareModel ();
//setters
userShares.add(userShareModel);
c.moveToNext();
}