我正在尝试从SQLite数据库表中读取所有条目。问题是光标每次只返回一个条目。我知道该表已有大约30个条目,因为当我尝试再次保存条目时,我会为每个条目收到此错误:
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: list.id (code 1555)
#################################################################
Error Code : 1555 (SQLITE_CONSTRAINT_PRIMARYKEY)
Caused By : Abort due to constraint violation.
(UNIQUE constraint failed: list.id (code 1555))
#################################################################
我在这里看到了几个关于类似问题的问题,但没有一个解决方案适合我。这是我到目前为止所尝试的:
public class Table
{
private static final String TABLE_NAME = "list";
// Column names
private static final String ID = "id";
private static final String INDEX = "index";
private static final String TITLE = "title";
private static final String CREATE_STATEMENT = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
"(" + ID + " INTEGER PRIMARY KEY, " + TITLE + " TEXT, " +
INDEX + " INTEGER)";
public static void create(SQLiteDatabase db)
{
db.execSQL(CREATE_STATEMENT);
}
public static void drop(SQLiteDatabase db)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
public static void saveList(SQLiteDatabase db, ArrayList<MyObject> list)
{
for (MyObject obj : list)
{
long id = insert(db, obj);
}
}
private static long insert(SQLiteDatabase db, MyObject obj)
{
final ContentValues values = new ContentValues();
values.put(ID, obj.getId());
values.put(INDEX, obj.getIndex());
values.put(TITLE, obj.getTitle());
return db.insert(TABLE_NAME, null, values);
}
public static ArrayList<MyObject> loadList(SQLiteDatabase db)
{
final ArrayList<MyObject> list = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
Log.d(TABLE_NAME, "Cursor size: " + cursor.getCount());
if (cursor.moveToFirst())
{
do
{
final long id = cursor.getLong(cursor.getColumnIndexOrThrow(ID));
final String title = cursor.getString(cursor.getColumnIndexOrThrow(TITLE));
final int index = cursor.getInt(cursor.getColumnIndexOrThrow(INDEX));
list.add(new MyObject(id, index, title);
}
while (cursor.moveToNext());
}
cursor.close();
return list;
}
}
我也尝试过使用cursor = db.query(TABLE_NAME, null, null, ..., null)
,但结果相同。
这就是我从SQLiteOpenHelper
类调用上述函数的方法:
public void saveList(ArrayList<MyObj> list)
{
final SQLiteDatabase db = getWritableDatabase();
Table.drop(db);
Table.create(db);
Table.saveList(db, list);
}
public ArrayList<MyObject> loadList()
{
return Table.loadList(getReadableDatabase());
}
我在同一个数据库中有另一个表,它具有非常相似的代码,但工作得很好。我一直试图解决这个问题一段时间,但我看不出可能会发生什么。任何帮助将不胜感激
答案 0 :(得分:2)
您的
有问题obj.getId()
private static long insert(SQLiteDatabase db, MyObject obj)
{
final ContentValues values = new ContentValues();
values.put(ID, obj.getId()); // check whether you are updating this with different value or not
values.put(INDEX, obj.getIndex());
values.put(TITLE, obj.getTitle());
return db.insert(TABLE_NAME, null, values);
}
答案 1 :(得分:0)
我遇到了同样的问题,尝试在表格中添加一个id字段(_id INTEGER PRIMARY KEY AUTOINCREMENT),一旦我添加了该字段,我就可以根据需要检索更多行