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

时间:2015-03-22 08:07:20

标签: android arraylist cursor duplicates

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

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();
        }

2 个答案:

答案 0 :(得分:0)

我这样做通常是这样的:

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


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

答案 1 :(得分:0)

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

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

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