我试图将sqlite表值传递给arraylistsqlite表的值正确显示,但是当它们传递给arraylist时。最后一行重复sqlite表中的行数,这意味着sqlite表中有2行,我得到2个索引arraylist,但是只有最后插入的行的值一次又一次地重复。请帮助我

 if (cursor.moveToFirst()) {
        do {
            roleTableModel.setId(cursor.getInt(cursor.getColumnIndex(RoleTableModel.ID)));
            Log.d("Role id", String.valueOf(cursor.getInt(cursor.getColumnIndex(RoleTableModel.ID))));
            roleTableModel.setName(cursor.getString(cursor.getColumnIndex(RoleTableModel.ROLE_NAME)));
            Log.d("Role Name", String.valueOf(cursor.getString(cursor.getColumnIndex(RoleTableModel.ROLE_NAME))));
            roleTableModel.setValue(cursor.getInt(cursor.getColumnIndex(RoleTableModel.ROLE_COUNT)));
            Log.d("Role Value", String.valueOf(cursor.getInt(cursor.getColumnIndex(RoleTableModel.ROLE_COUNT))));
            roleDetails.add(roleTableModel);

最佳答案

每次在loop中,您都需要创建RoleTableModel的新实例,如下所示:

        if (cursor.moveToFirst()) {
                do {
                    roleTableModel = new RoleTableModel();//<--add this line
 roleTableModel.setId(cursor.getInt(cursor.getColumnIndex(RoleTableModel.ID)));
                    Log.d("Role id", String.valueOf(cursor.getInt(cursor.getColumnIndex(RoleTableModel.ID))));
                    roleTableModel.setName(cursor.getString(cursor.getColumnIndex(RoleTableModel.ROLE_NAME)));
                    Log.d("Role Name", String.valueOf(cursor.getString(cursor.getColumnIndex(RoleTableModel.ROLE_NAME))));
                    roleTableModel.setValue(cursor.getInt(cursor.getColumnIndex(RoleTableModel.ROLE_COUNT)));
                    Log.d("Role Value", String.valueOf(cursor.getInt(cursor.getColumnIndex(RoleTableModel.ROLE_COUNT))));
                    roleDetails.add(roleTableModel);
        }while(cursor.moveToNext());

08-05 13:13