3
0

More than 3 years have passed since last update.

【Android】【初心者向け】RoomのAutoIncrement(PrimaryKeyのautogenerate = true)の値は、0で良い

Posted at

【Android】【初心者向け】 RoomのAutoIncrement(PrimaryKeyのautogenerate = true)の値は、0で良い

概要

タイトル通りですが、AndroidのRoomのAutoincrement(PrimaryKeyのautogenerate = true)の値は、0で良いという話です。

今まで、業務でRoomを使う経験がなく、 ドキュメントやサンプルコードを見ていて、
AutoIncrementのときに、何を渡せば良いのかわからず、どこかで見たサンプルと同じように0を渡しすようにしていました。
ただふとこれで正しいのかと気になり、調べてみて良かったということに気づいたという話です。

参考にしたもの

developers: Primarykey

以下は、引用です。

autoGenerate

public boolean autoGenerate ()
Set to true to let SQLite generate the unique id.

When set to true, the SQLite type affinity for the field should be INTEGER.

If the field type is long or int (or its TypeConverter converts it to a long or int), Insert methods treat 0 as not-set while inserting the item.

If the field's type is Integer or Long (or its TypeConverter converts it to an Integer or a Long), Insert methods treat null as not-set while inserting the item.

つまり、以下のような内容かと思います。

  • autoGenerateをtrueにすると、SQLiteがユニークなIDを生成するよ
  • 型が longintのときは、insertのメソッドは、0を未設定として扱うよ
  • 型が、LongIntegerのときは、insertのメソッドは、nullを未設定として扱うよ

そして、基本的にはkotlinのintを使うかと思いますので、0を設定してあげるのが良いということになるかと思います。

コード的なイメージ

仮にUserというEntityを使う場合ですが、以下のようになるのかと思います。

UserEntity.kt
@Entity(tableName = "users")
data class User(
  // デフォルト引数に0を設定
  @PrimaryKey(autoGenerate = true) val id: Int = 0,
  @ColumnInfo(name ="name") val name: String
)
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0