1555 android data_error ai_generated true

android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: users.id (code 1555)

ID: android/room-insert-null-primary-key

Also available as: JSON · Markdown · 中文
92%Fix Rate
88%Confidence
1Evidence
2024-09-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Room 2.6.1 active
SQLite 3.44.0 active
Android 14 (API 34) active

Root Cause

Room entity has a non-null primary key field that is not auto-generated, but null value is provided during insert.

generic

中文

Room 实体具有非空主键字段且非自动生成,但插入时提供了空值。

Workarounds

  1. 95% success Add @PrimaryKey(autoGenerate = true) to the id field. Example: @PrimaryKey(autoGenerate = true) val id: Long = 0. This auto-generates unique IDs.
    Add @PrimaryKey(autoGenerate = true) to the id field. Example: @PrimaryKey(autoGenerate = true) val id: Long = 0. This auto-generates unique IDs.
  2. 85% success 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.
    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.

中文步骤

  1. Add @PrimaryKey(autoGenerate = true) to the id field. Example: @PrimaryKey(autoGenerate = true) val id: Long = 0. This auto-generates unique IDs.
  2. 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.

Dead Ends

Common approaches that don't work:

  1. Set primary key field to nullable in entity class 95% fail

    Room does not allow nullable primary keys; will cause compile error or runtime crash.

  2. Use @Ignore on primary key field to skip Room processing 90% fail

    Ignores the field entirely, but then no primary key exists, breaking database operations.