In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains the "Android development Jetpack components Room how to use", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Android development Jetpack components Room how to use" it!
I. brief introduction
Room is a database ORM framework officially launched by Google. ORM refers to Object Relational Mapping, that is, object-relational mapping, that is, mapping relational databases to object-oriented languages. Using the ORM framework, we can manipulate relational databases with object-oriented thinking, eliminating the need to write SQL statements.
Second, import apply plugin: 'kotlin-kapt'dependencies {... implementation' androidx.room:room-runtime:2.2.5' kapt' androidx.room:room-compiler:2.2.5'} 3. Use
The use of Room can be divided into three steps:
Create the Entity class: that is, the entity class, each entity class generates a corresponding table and each field generates a corresponding column.
Create Dao class: Dao refers to Data Access Object, that is, data access object. Usually, we will encapsulate the operation of adding, deleting, modifying and querying the database. In this way, the logic layer does not need to deal with the database, but only needs to use the Dao class.
Create the Database class: define the version of the database, the tables contained in the database, the Dao classes contained, and the database upgrade logic.
3.1Creating Entity classes
Create a new User class and add the @ Entity annotation to have Room automatically create a table for this class. Add @ PrimaryKey (autoGenerate = true) annotation to the primary key to make the id increase itself, so you might as well write the primary key id here in a fixed way.
@ Entitydata class User (var firstName: String, var lastName: String, var age: Int) {@ PrimaryKey (autoGenerate = true) var id: Long = 0} 3.2 create Dao class
Create an interface class UserDao and add @ Dao annotations to this class. Add @ Insert, @ Delete, @ Update, and @ Query annotations for the add, delete, change and search methods, respectively. @ Query needs to write a SQL statement to implement the query. Room automatically generates these database manipulation methods for us.
Daointerface UserDao {@ Insert fun insertUser (user: User): Long @ Update fun updateUser (newUser: User) @ Query ("select * from user") fun loadAllUsers (): List @ Query ("select * from User where age >: age") fun loadUsersOlderThan (age: Int): List @ Delete fun deleteUser (user: User) @ Query ("delete from User where lastName =: lastName") fun deleteUserByLastName (lastName: String): Int}
The @ Query method is not limited to lookup, but you can also write our custom SQL statement, so you can use it to perform special SQL operations, as shown in the deleteUserByLastName method in the example above.
3.3.Create Database abstract classes
Create a new AppDatabase class, inheriting from the RoomDatabase class, and add the @ Database annotation to declare the version number and the included entity class. And declare the abstract method that gets the Dao class in the abstract class.
Database (version = 1, entities = [User::class]) abstract class AppDatabase: RoomDatabase () {abstract fun userDao (): UserDao companion object {private var instance: AppDatabase? = null @ Synchronized fun getDatabase (context: Context): AppDatabase {return instance?.let {it}?: Room.databaseBuilder (context.applicationContext, AppDatabase::class.java) "app_database") .build () .apply {instance = this}
In the getDatabase method, the first parameter must use applicationContext to prevent memory leaks, and the third parameter represents the name of the database.
3.4 Test
There are only four buttons with id btnAdd,btnDelete,btnUpdate,btnQuery in the layout, so the layout code is no longer given.
The MainActivity code is as follows:
Class MainActivity: AppCompatActivity () {override fun onCreate (savedInstanceState: Bundle?) {super.onCreate (savedInstanceState) setContentView (R.layout.activity_main) val userDao = AppDatabase.getDatabase (this). UserDao () val teacher = User ("lin", "guo", 66) val student = User ("alpinist", "wang") 3) btnAdd.setOnClickListener {thread {teacher.id = userDao.insertUser (teacher) student.id = userDao.insertUser (student)} btnDelete.setOnClickListener {thread {userDao.deleteUser (student)}} btnUpdate.setOnClickListener { Thread {teacher.age = 666 userDao.updateUser (teacher)}} btnQuery.setOnClickListener {thread {Log.d ("~ ~") "${userDao.loadAllUsers ()}")}
We have opened a new thread for each operation, which is because the database operation involves IO, so it is not recommended to perform it on the main thread. In the development environment, we can also allow the main thread to manipulate the database through the allowMainThreadQueries () method, but this method must not be used in a formal environment.
Room.databaseBuilder (context.applicationContext, AppDatabase::class.java, "app_database"). AllowMainThreadQueries (). Build ()
Click btnAdd, then click btnQuery,Log as follows:
~ ~: [User (firstName=lin, lastName=guo, age=66), User (firstName=alpinist, lastName=wang, age=3)]
Click btnDelete, then click btnQuery,Log as follows:
~ ~: [User (firstName=lin, lastName=guo, age=66)]
Click btnUpdate, then click btnQuery,Log as follows:
~ ~: [User (firstName=lin, lastName=guo, age=666)]
Thus it can be seen that our operations of adding, deleting, changing and searching have been successful.
IV. Database upgrade 4.1 simple upgrade
Using fallbackToDestructiveMigration (), you can simply and rudely upgrade, that is, simply discard the old version of the database, and then create the latest database
Room.databaseBuilder (context.applicationContext, AppDatabase::class.java, "app_database") .fallbackToDestructiveMigration () .build ()
Note: this method is too violent and can be used during the development phase and cannot be used in a formal environment because it will result in the loss of the old version of the database.
4.2 Specification upgrade 4.2.1 add a table
Create an Entity class
@ Entitydata class Book (var name: String, var pages: Int) {@ PrimaryKey (autoGenerate = true) var id: Long = 0}
Create a Dao class
Daointerface BookDao {@ Insert fun insertBook (book: Book) @ Query ("select * from Book") fun loadAllBooks (): List}
Modify the Database class:
@ Database (version = 2, entities = [User::class, Book::class]) abstract class AppDatabase: RoomDatabase () {abstract fun userDao (): UserDao abstract fun bookDao (): BookDao companion object {private var instance: AppDatabase? = null privateval MIGRATION_1_2 = object: Migration (1 2) {override fun migrate (database: SupportSQLiteDatabase) {database.execSQL ("" create table Book (id integer primary key autoincrement not null, name text not null) Pages integer not null) ".trimIndent ()}} @ Synchronized fun getDatabase (context: Context): AppDatabase {return instance?.let {it}?: Room.databaseBuilder (context.applicationContext, AppDatabase::class.java) "app_database") .addMigrations (MIGRATION_1_2) .build () .apply {instance = this}
Note: the changes here are:
Version upgrade
Add the Book class to the entities
New abstract method bookDao
Create a Migration object and add it to the builder of getDatabase
Now if you manipulate the database again, you will add a new Book table.
4.2.2 modify a table
For example, add an author field to Book
@ Entitydata class Book (var name: String, var pages: Int, var author: String) {@ PrimaryKey (autoGenerate = true) var id: Long = 0}
Modify Database to add the migration logic for versions 2 to 3:
@ Database (version = 3, entities = [User::class, Book::class]) abstract class AppDatabase: RoomDatabase () {abstract fun userDao (): UserDao abstract fun bookDao (): BookDao companion object {private var instance: AppDatabase? = null privateval MIGRATION_1_2 = object: Migration (1 2) {override fun migrate (database: SupportSQLiteDatabase) {database.execSQL ("" create table Book (id integer primary key autoincrement not null, name text not null) Pages integer not null) "" .trimIndent ()}} privateval MIGRATION_2_3 = object: Migration (2) 3) {override fun migrate (database: SupportSQLiteDatabase) {database.execSQL ("" alter table Book add column author text not null default "unknown".trimIndent ())}} @ Synchronized fun getDatabase (context: Context) AppDatabase {return instance?.let {it}?: Room.databaseBuilder (context.applicationContext AppDatabase::class.java, "app_database") .addMigrations (MIGRATION_1_2, MIGRATION_2_3) .build () .apply {instance = this}
Note: the changes here are:
Version upgrade creates a Migration object and adds it to the builder of getDatabase
4.3 Test
Modify MainActivity:
Class MainActivity: AppCompatActivity () {override fun onCreate (savedInstanceState: Bundle?) {super.onCreate (savedInstanceState) setContentView (R.layout.activity_main) val bookDao = AppDatabase.getDatabase (this). BookDao () btnAdd.setOnClickListener {thread {bookDao.insertBook (Book (first Line of Code), 666 "guolin")}} btnQuery.setOnClickListener {thread {Log.d ("~ ~", "${bookDao.loadAllBooks ()}")}
Click btnAdd, then click btnQuery,Log as follows:
~ ~: [Book (first line of name=, pages=666, author=guolin)]
This means that our two upgrades to the database have been successful.
Thank you for your reading, the above is the "Android development of Jetpack components Room how to use" the content, after the study of this article, I believe you on the Android development of Jetpack components Room how to use this problem has a deeper understanding, the specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.