简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM