Using Anko and Kotlin to develop databases on Android: SQLite is never easy (KAD25)

Source: Internet
Author: User

Antonio Leiva

Time:Mar.

Original link:https://antonioleiva.com/databases-anko-kotlin/

facts Tell us: in writing a database in Android is pretty boring.

Use SQLite , all the templates you need are not the most enjoyable things in the world today.

Fortunately, in the latest One of the things that they announcedat Google I/O meetings, called the "guest bedroom,"was to create enough libraries to streamline the work.

However, Use Anko , we can still continue to work like a low-level framework, but get rid of some of the tedious parts of the implementation process . Today, let's see what we can do.

Use Anko to create your database

Here you will see how to create a database from scratch. on Android , you need to Sqliteopenhelper toretrieve the database. After that, you also need to remember to close it after the request. And these Anko have been done for you.

To maintain, you need to add the Anko sqlite dependency relationship:

1 compile ' org.jetbrains.anko:anko-sqlite:0.10.0 '

ImplementManagedsqliteopenhelper

If you use this inheritance SQLiteOpenHelper class, you can create code blocks that manipulate the database as follows:

12     ... 3 }

inside curly braces is SQLiteDatabase class, so you can invoke its method directly. In addition, This table is opened only before this code is executed. It is closed after the execution of the code is complete .

How do we implement this class? Based on the anko documentation, the recommended method is:

1 classMysqlhelper (Ctx:context): Managedsqliteopenhelper (CTX, "MyDB") {2  3 Companion Object {4         Privatevar instance:mysqlhelper? =NULL5  6 @Synchronized7 Fun getinstance (ctx:context): mysqlhelper {8             if(Instance = =NULL) {9Instance =Mysqlhelper (Ctx.applicationcontext)Ten             } One             returninstance!! A         } -     } -   the Override Fun OnCreate (db:sqlitedatabase) { -     } -   - Override Fun Onupgrade (Db:sqlitedatabase, Oldversion:int, newversion:int) { +     } -   + } A   at //Access Property for Context - Val Context.database:MySqlHelper -Get () = Mysqlhelper.getinstance (ApplicationContext)

we create a short single routine that saves Helper instances, using synchronous methods to make different threads unable to generate multiple instances.

In addition, we create an extended property for the context so that any need Context classes have direct access to the database.

This is the most initial code that allows us to use it.

Defining the database table structure

in order to create our database, we need to implement Helper 's onCreater method and use the provided by Anko createTable extension functions:

1 Override Fun OnCreate (db:sqlitedatabase) {2     true , 3             " _id "to-INTEGER + Primary_key,4             " name " to-TEXT,5             " surname "to TEXT,6             "age" to INTEGER)7 }

The first parameter here gives the database name, and the second parameter indicates whether to create before, make sure that the table does not exist.

The third parameter is vararg (变量) the pair. That is, you can add any number of variables. As you can see, the format of this variable pair is A to B . This infix function, which is decorated with reserved words, is called the infix function (infixfunctions).

the second part of the variable pair is SqlType class constants. Since this is interesting, I suggest you look at its implementation. Here, it skillfully uses the operator Overloads .

inserting and querying data

Use Anko Everything has become much easier. In the insert process, you do not need to create your own ContentValue to add all the data, but instead use the extension function of the database object. This will allow you to:

1 Database.use {2     Insert ("person",3             "_id" to 1,4              ' name ' to ' John ',5             ' surname ' to ' Smith ',6             ' age ' To)7 }

while querying, there are several ways to do it. In one of these, you can add a name to the variable for the query 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")

there is another method that is more similar to Used in the Android Framework, allowing for subsequent use of the Ask symbol and value. In this case, they must all be String :

1 Select ("Person")2         . Wheresimple ("(_id =?) and (name =?) " , 3                 1.toString (), "John")

I personally think the second approach is simpler.

You can also use all database general operations, such as limit , orderBy , having or groupBy . You can See all of these actions in the Anko documentation.

in order to process the result cursor, Anko It also gives us different functions. , such as parseSingle (to a result) or parseList (for several results). These functions receive one rowParser .

There are many different parsers. is one of the MapRowParser interesting things that maps a column to a graph (map).

using this parser and map delegate, you can directly parse the values in the diagram into the class. Can See this note in my book .

Conclusion

While there are many libraries that can simplify much of the work of a database, for simplicity, the Anko is enough.

Because it simplifies many of the painful things that we do with databases, it's a good choice for simplifying database work.

In addition, it shows us how to use languages in other ways, which are useful when you encounter problems.

don't forget to look. Previous Articles to learn more about Kotlin!

Using Anko and Kotlin to develop databases on Android: SQLite is never easy (KAD25)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.