1. 程式人生 > >Databases on Android with Anko and Kotlin: SQLite never was so easy

Databases on Android with Anko and Kotlin: SQLite never was so easy

Truth to be told: writing databases in Android is quite boring.

All the boilerplate required to work with SQLite is far from being the most delightful thing in the world.

Fortunately, there are already enough libraries that simplify this task, one of them announced during the latest Google I/O, called

Room.

With Anko, however, we can continue to work as low-level as when we use the framework, but get rid of some of the more tedious parts of its implementation. Today we’ll see how.

Create your database with Anko

You’ll see here how to create your database from scratch. On Android, you’ll need a SQLiteOpenHelper

, which you use to retrieve the database. You’ll then need to remember to close after the requests. Anko does this for you.

For this you need to include SQLite dependency for Anko:

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

Implement ManagedSQLiteOpenHelper

If you use this class, which extends SQLiteOpenHelper, you can create blocks of code where you will execute the database operations, as follows:

Want to learn Kotlin?

Check my free guide to create your first project in 15 minutes!

123 database.use{...}

The content inside the braces is an extension function on the SQLiteDatabase class, so you can call its methods directly. With the added point that the table will be open just before and closed right after executing this block.

How do we implement this class? Based on Anko’s documentation, the recommended way is:

12345678910111213141516171819202122232425 classMySqlHelper(ctx:Context):ManagedSQLiteOpenHelper(ctx,"mydb"){companionobject{privatevarinstance:MySqlHelper?=null@Synchronizedfun getInstance(ctx:Context):MySqlHelper{if(instance==null){instance=MySqlHelper(ctx.applicationContext)}returninstance!!}}override fun onCreate(db:SQLiteDatabase){}override fun onUpgrade(db:SQLiteDatabase,oldVersion:Int,newVersion:Int){}}// Access property for Contextval Context.database:MySqlHelperget()=MySqlHelper.getInstance(applicationContext)

We create a small singleton that will save the instance of the helper, in a synchronized way so that different threads can not generate more than one instance.

In addition, we create an extension property for the context, so that any class that requires Context can access the database directly.

This allows us to make use of the initial code.

Define the table structure

To create our database, all we have to do is implement the onCreate method of the helper, and use the createTable extension function provided by Anko:

1234567 override fun onCreate(db:SQLiteDatabase){db.createTable("Person",true,"_id"toINTEGER+PRIMARY_KEY,"name"toTEXT,"surname"toTEXT,"age"toINTEGER)}

The first parameter is the name of the database, and the second parameter checks that the table doesn’t exist before doing the create.

The third is a vararg pair. That is, you can add as many as you like. As you can see, the pairs are created with the form A to B. This is called infix function, and is specified with the reserved word infix.

The second part of the pairs are constants of the SqlType class. I recommend that you take a look at the implementation, because it’s very interesting. Here it makes a clever use of the operator overloading.

Insert and query data

Everything becomes much easier with Anko. Instead of having to create your own ContentValue to add all the data during insertion, you can use an extension function on the database object, which is such that:

1234567 database.use{insert("Person","_id"to1,"name"to"John","surname"to"Smith","age"to20)}

For queries, there are several ways to do them. In one of them you can add names to the variables of the query and include the values as pairs:

1234 select("Person").where("(_id = {id}) and (name = {name})","id"to1,"name"to"John")

And there is another, more similar to that used in the Android framework, which allows to include interrogation sign and values more later. All of them must be String in this case:

123 select("Person").whereSimple("(_id = ?) and (name = ?)",1.toString(),"John")

Personally in this case I find the second option simpler.

You can also apply all regular database operations such as limit, orderBy, having or groupBy. You can see all the operations in Anko documentation.

To deal with the resulting cursor, Anko also provides us with different functions, such as parseSingle (for one result) or parseList (for several). These functions receive a rowParser.

There are a lot of different parsers. One interesting is the MapRowParser, which maps the columns to a map.

With this parser and map delegate, you can parse directly the values from a map to a class. You can see this explained in my book.

Conclusion

While it’s true that there are libraries that simplify much more the work with databases, for simple things Anko can be more than enough.

It saves us many of the things that make working with databases really painful, so it’s a good alternative for simple databases.

In addition, it shows us other ways to use language that can be very useful when you are facing other problems.

Don’t forget take a look at the previous articles to learn more about Kotlin!

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.

Shares

Like this:

Like Loading...

相關推薦

Databases on Android with Anko and Kotlin: SQLite never was so easy

Truth to be told: writing databases in Android is quite boring. All the boilerplate required to work with SQLite is far from being the most delightfu

Dialogs and alerts on Android using Anko and Kotlin

Creating alerts and dialogs on Android is a relatively simple task thanks to the builder, but due to the verbosity of the language it usually becomes

How to make unit test on Android with Kotlin (KAD 22)

Of course, Kotlin also allows us to do unit tests in a very simple way, and very similar to what we’re used in Java. There are some small complicatio

How to use Retrofit on android with Kotlin (KAD 21)

This is just one more example about how in Kotlin we can continue to use the same libraries we’ve always used in Java for Android. Retrofit is a libr

How to use Dagger 2 on Android with Kotlin (KAD 20)

Virtually everyone who wants to create code on Android in a decoupled and easy-to-test way, resorts to Dagger sooner or later. Although there is some

Mirror android phone's screen and gain full control on computer with Vysor

Looking for a tool that could mirror non-rooted android phone's screen and allow user to gain a full control on computer? Here is a good

[PWA] Add Push Notifications to a PWA with React in Chrome and on Android

On Android and in Chrome (but not on iOS), it's possible to send push notifications with a PWA. We'll start by asking the user for permission to send them

AnkoKotlin實現Android上的對話框和警告提示(KAD 24)

posit eve linear 免費 clas testing size uil 如何 作者:Antonio Leiva 時間:Mar 9, 2017 原文鏈接:https://antonioleiva.com/dialogs-android-anko-kotlin/

Count the consecutive zero bits (trailing) on the right with multiply and lookup

驗證 %d vol tip inf mat cit number failed 我在網上看到了一點神奇的代碼,用來計算一個數字末尾連續零的個數。 剛好我在優化一個I2C讀寫函數(只寫入I2C特定bit),覺得這個很有用。經過嘗試,確實沒問題。 下面我隆重介紹一下: Coun

A feasibility study on SSVEP-based interaction with motivating and immersive virtual and augmented r

A feasibility study on SSVEP-based interaction with motivating and immersive virtual and augmented reality 基於SSVEP的互動與刺激和沉浸式虛擬和增強現實的可行性研究

Clean architecture for Android with Kotlin: a pragmatic approach

Clean architecture is a topic that never gets old in the Android world, and from the comments and questions I receive, I feel it’s still not very cle

Image resize on-the-fly with Lambda and S3

A crash course on Serverless with AWS — Image resize on-the-fly with Lambda and S3Handling large images has always been a pain in my side since I started w

We built our iOS and Android apps in Java & Kotlin

We built our iOS and Android apps in Java & Kotlin — one year laterMonday morning, first cappuccino, first lines of a new feature we’re adding to our m

Tracking transactions on the blockchain with nodejs and kafka

Tracking transactions on the blockchain with nodejs and kafkaIn this blog post im going to give some insight into a project that i did recently with nodes

Correct the ImageView's adjustViewBounds behaviour on API Level 17 and below with AdjustableImageView

A requirement that almost every single application has is "I want to scale up an ImageView proportionally to fit its parent. How can I do

Some Thoughts on Android's new ConstraintLayout and Android Studio's new Design Editor

At this year's IO Google introduced a new layout - the ConstraintLayout - and also presented it's totally revamped la

Marginally Interesting: What is going on with DeepMind and Google?

Tweet As you might have heard, Google has acquired DeepMind, a London b

Working with Django and Flask on Nitrous.IO – Real Python

This is a guest post by our friend Greg McKeever from Nitrous.IO. Nitrous.IO is a platform which allows you to spin up your own development environment

Experimenting with TensorFlow on Android Part 1

Let us start by installing TensorFlow, I tried a couple methods of installing it and ended up using dockerdocker run -it gcr.io/tensorflow/tensorflow:lates

In-app purchases on Android: new and upcoming

In-app purchases on Android: new and upcomingA closer look at the I/O 2018 announcementsGoogle I/O 2018 is just behind us, but it brought a lot of news whe