1555
android
data_error
ai_generated
true
android.database.sqlite.SQLiteConstraintException: NOT NULL 约束失败: users.id (代码 1555)
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: users.id (code 1555)
ID: android/room-insert-null-primary-key
92%修复率
88%置信度
1证据数
2024-09-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Room 2.6.1 | active | — | — | — |
| SQLite 3.44.0 | active | — | — | — |
| Android 14 (API 34) | active | — | — | — |
根因分析
Room 实体具有非空主键字段且非自动生成,但插入时提供了空值。
English
Room entity has a non-null primary key field that is not auto-generated, but null value is provided during insert.
解决方案
-
Add @PrimaryKey(autoGenerate = true) to the id field. Example: @PrimaryKey(autoGenerate = true) val id: Long = 0. This auto-generates unique IDs.
-
If auto-generate not desired, ensure you assign a non-null value before insert: user.id = System.currentTimeMillis() or use UUID.randomUUID().toString() for string keys.
无效尝试
常见但无效的做法:
-
Set primary key field to nullable in entity class
95% 失败
Room does not allow nullable primary keys; will cause compile error or runtime crash.
-
Use @Ignore on primary key field to skip Room processing
90% 失败
Ignores the field entirely, but then no primary key exists, breaking database operations.