Using Anko and Kotlin to develop databases on Android: SQLite is never an easy task (KAD25). ankokotlin
By Antonio Leiva
Time: Mar 30,201 7
Link: https://antonioleiva.com/databases-anko-kotlin/
The fact tells us that writing a database in Android is quite boring.
When using SQLite, all the required templates are not the most pleasant thing in the world today.
Fortunately, one of the items they announced at the latest Google I/O conference (called Room) was to develop enough libraries to simplify the work.
However,ApplicationAnko, We can continue to work like using a low-level framework,Get rid of some tedious parts in the implementation process. Today, let's see how it works.
Use Anko to create your database
Here you will see how to create a database from scratch. On Android, you need SQLiteOpenHelper to retrieve the database. After that, you also need to remember to close it after the request. And these Anko have done it for you.
Maintain. You need to add the SQLite dependency of Anko:
1 compile 'org.jetbrains.anko:anko-sqlite:0.10.0'
Implement ManagedSQLiteOpenHelper
If you use this inheritanceSQLiteOpenHelper
You can create a code block to operate the database, as shown below:
1 database.use { 2 ...3 }
In braces:SQLiteDatabase
Class Extension function, so that you can directly call its method. In addition,Open the table only before executing the code. Close the code after it is executed..
How can we implement this class? The recommended method for Anko-based documents is:
1 class MySqlHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "mydb") { 2 3 companion object { 4 private var instance: MySqlHelper? = null 5 6 @Synchronized 7 fun getInstance(ctx: Context): MySqlHelper { 8 if (instance == null) { 9 instance = MySqlHelper(ctx.applicationContext)10 }11 return instance!!12 }13 }14 15 override fun onCreate(db: SQLiteDatabase) {16 }17 18 override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {19 }20 21 }22 23 // Access property for Context24 val Context.database: MySqlHelper25 get() = MySqlHelper.getInstance(applicationContext)
We create a short single routine, which saves the helper instance and uses the synchronous method to prevent different threads from generating multiple instances.
In addition, we create an extended attribute for the context.Context
Can directly access the database.
This is the initial code that allows us to use.
Define database table structure
To create our database, we need to implement the helperonCreater
Method, and usecreateTable
Extended functions:
1 override fun onCreate(db: SQLiteDatabase) {2 db.createTable("Person", true,3 "_id" to INTEGER + PRIMARY_KEY,4 "name" to TEXT,5 "surname" to TEXT,6 "age" to INTEGER)7 }
Here, the first parameter indicates the database name, and the second parameter indicates whethercreate
Before, make sure the table does not exist.
The third parameter isvararg
(Variable)
Yes. That is, you can add any number of variables. As you can see, the format of this variable pair isA to B
. Use Reserved Wordsinfix
The modified function is calledInfix Function(Infix function).
The second part of the variable pair isSqlType
Class constant. Because it is interesting, I suggest you look at its implementation. Here, it cleverly uses Operator overloading.
Insert and query data
It's much easier to use Anko. You do not need to create your ownContentValue
To add all the data, but to use the database object extension function. In this way, you can:
1 database.use {2 insert("Person",3 "_id" to 1,4 "name" to "John",5 "surname" to "Smith",6 "age" to 20)7 }
Query can be performed in several ways. One of them is that you can add a name for the queried variable and add the value as a variable pair:
1 select("Person")2 .where("(_id = {id}) and (name = {name})",3 "id" to 1,4 "name" to "John")
Another method is similar to the Android framework, where the querymark and value can be used later. In this case, both must beString
:
1 select("Person")2 .whereSimple("(_id = ?) and (name = ?)",3 1.toString(), "John")
I personally think the second method is simpler.
You can also use all common database operations, suchlimit
,orderBy
,having
OrgroupBy
. You can see all these operations in the Anko document.
To process the result cursor, AnkoDifferent functions are also provided for us., SuchparseSingle
(For a result) orparseList
(For several results ). These functions receiverowParser
.
There are many different Resolvers.MapRowParser
Is an interesting one. It maps columns to a map.
Use this parser andmap
Delegate, you can directly parse the values in the graph into the class. You can see this in my book.
Conclusion
Although there are many databases that can simplify a lot of the work of the database, Anko is enough to simplify the work.
Because it simplifies a lot of the pain points of using the database, it is a good choice to simplify the database work.
In addition, it shows us how to use languages in other ways. These languages are useful when you encounter problems.
Don't forget to read the previous articles.