Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Android版 nanaとデータの永続化とDatabase

Young
August 13, 2018

Android版 nanaとデータの永続化とDatabase

社内勉強会の資料です #深いい勉強会

Young

August 13, 2018
Tweet

More Decks by Young

Other Decks in Programming

Transcript

  1. Ormaͱ͸ • Object Relational Mapper • SQLiteΛѻ͏σʔλϕʔε ϥΠϒϥϦ • Ξϊςʔγϣϯ

    ϓϩηοαʔͰॲཧΛੜ੒ • RelationΛؚΊͯEntity Classʹهड़͕Ͱ͖Δ • গͳ͍มߋͰ͋Ε͹ϚΠάϨʔγϣϯίʔυΛॻ͔ͳͯ͘΋Α͍ • SQL QueryΛࣗಈੜ੒ɻSQL QueryΛॻ͔ͳͯ͘ྑ͍
  2. Roomͱ͸ • Object Mapper • SQLiteΛѻ͏σʔλϕʔε ϥΠϒϥϦ • Ξϊςʔγϣϯ ϓϩηοαʔͰॲཧΛੜ੒

    • SQL QueryΛॻ͘ඞཁ͕͋Δ • SQL QueryΛͰ͖ΔݶΓίϯύΠϧ࣌ʹݕূ • SQL ͱ Java/Kotlin ؒͷܕ҆શʹରԠ • LiveData/RxJavaͰͷςʔϒϧ؂ࢹ • Unit Test΋૝ఆ • ϚΠάϨʔγϣϯͷςετίʔυΛॻ͚ΔͷͰ҆৺
  3. Roomͷಛ௃ • SQLΛӅṭ͠ͳ͍ • JavaͰSQLΫΤϦΛ૊ΈཱͯͨΓ͸͠ͳ͍ • ΫΤϦ͸جຊతʹಉظతʹ࣮ߦ • ඇಉظॲཧ͸LiveData΍RxJavaͳͲʹ೚ͤΔ •

    ߏ੒͕Retrofit΍Daggerʹ͍ۙͷͰཧղ͠΍͍͢ɺಋೖ͠΍͍͢ • TableؒͷRelationͷఆٛ͸Entity্ͰߦΘͳ͍
  4. Room جຊཁૉ • Database • σʔλϕʔεຊମ • Entity • ςʔϒϧ

    / ͦͷςʔϒϧͷ 1 ߦΛද͢ • DAO (Data Access Object) • SQL ΫΤϦʔͱ Java/Kotlin ϝιουͷؔ࿈෇͚
  5. Database private const val DB_NAME = "app.db" @Database(entities = [(User::class)],

    version = 1) abstract class UserDatabase : RoomDatabase() { abstract fun userDao(): UserDao companion object { @Volatile private var INSTANCE: UserDatabase? = null @JvmStatic fun getInstance(context: Context): UserDatabase = INSTANCE ?: synchronized(this) { INSTANCE ?: buildDatabase(context).also { INSTANCE = it } } private fun buildDatabase(context: Context) = Room.databaseBuilder(context.applicationContext, UserDatabase::class.java, DB_NAME) .build() } }
  6. Entity @Entity(tableName = “user”, indices = [Index(value = ["username"], unique

    = true)]) data class User(@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") var id: Int = 0, @ColumnInfo(name = "username") var userName: String? = null
  7. Entity @Dao interface UserDao { @Query("SELECT * FROM user WHERE

    _id = :id") fun getUserById(id: Int): Flowable<User> @Query("SELECT * FROM user ORDER BY username DESC") fun getAllUser(): List<User> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertUser(user: User): Long @Query("SELECT COUNT(_id) FROM user") fun getNumberOfRows(): Int @Query("DELETE FROM user") fun deleteAllUser() }