Trần Đức Tâm
Trần Đức Tâm

Reputation: 4443

Content provider in Android by Kotlin

everyone!

I created a side application for practice Kotlin in Android. I create a provider like that:

class TestProvider : ContentProvider() {
    companion object {
        val sUriMatcher = UriMatcher(UriMatcher.NO_MATCH)
        val MATCH_WITH_TEST = 0

        init {
            sUriMatcher.addURI("$APPLICATION_ID.provider", TestEntity.TABLE_NAME, MATCH_WITH_TEST)
        }
    }

    var mDatabaseHelper: LocalSQLiteHelper? = null

    override fun onCreate(): Boolean {
        mDatabaseHelper = LocalSQLiteHelper(context)
        return true
    }

    override fun insert(uri: Uri?, values: ContentValues?): Uri? {
        if (mDatabaseHelper != null && !mDatabaseHelper?.writableDatabase?.isReadOnly) {

        }

        return uri
    }
}

You see! The content provider has to contain a Database Helper. This Database Helper only created at onCreate() method of the parent class.

So now I want to check the writableDatabase be a read-only database or not. Because the mDatabaseHelper is LocalSQLiteHelper? so !mDatabaseHelper?.writableDatabase?.isReadOnly code return Boolean? which not accepted in Kotlin if control statement.

Have any one got the same problem with me?

Update:

I found a solution by using:

val database: SQLiteDatabase = mDatabaseHelper?.writableDatabase as SQLiteDatabase

It work but I dont know why?

Upvotes: 1

Views: 1672

Answers (1)

dniHze
dniHze

Reputation: 2232

Just use let:

override fun insert(uri: Uri?, values: ContentValues?): Uri? {
    mDatabaseHelper?.let {
        if (it.writableDatabase.isReadOnly) {

        }
    }

    return uri
}

?.let { it -> ... } gives you database helper object inside of a closure if it's not null.

Upvotes: 3

Related Questions