AnKo SQLite : populate listview asynchronously from database?

120 views Asked by At

I'm trying to translate my app from Java to Kotlin. I'm managing database with AnKo SQLite

All is OK except listviews with CursorLoaders : I can't find how to replace CursorLoader while using AnKo SQLite. (and same problem with expandableListViews)

Can somebody help me please?

1

There are 1 answers

0
Bob33700 On BEST ANSWER

OK, here is my solution... I don't know if it is the best :

  1. create a new kotlin class "MyCursorLoader" that extends CursorLoader
  2. set the primary constructor like this :

    class MyCursorLoader( mContext: Context, val mTableName: String, var mProjection: Array<String>? = null, var mSelection: String = "1", var mSelectionArgs: Array<String> = emptyArray(), var mGroupBy: String = MySqlHelper.ID, var mHaving: String = "", var mSortOrder: String = "${MySqlHelper.ID} ASC", var mLimit: String = "", var mDistinct: Boolean = true ): CursorLoader(mContext) { val mObserver: Loader<Cursor>.ForceLoadContentObserver = Loader<Cursor>(mContext).ForceLoadContentObserver() var mCancellationSignal: CancellationSignal? = null

  3. override the OnLoadInBackground method with te same code than built-in one, just replacing the val cursor = ContentResolverCompat.query(... line with :

    val cursor = MySqlHelper.instance.readableDatabase.query(
        mDistinct, mTableName, mProjection, mSelection, mSelectionArgs, mGroupBy, mHaving, mSortOrder, mLimit, mCancellationSignal)
    

So no need to recreate a dataprovider in manifest, no need to deal with Uri's... I can use MyCursorLoader exactly like built-in CursorLoader, calling it like this :

    override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> {
        when (id) {
            DAY_HEADER_LOADER ->
                return MyCursorLoader(mContext, TABLE_EVENTS, arrayOf(ID, DAY), mGroupBy = DAY, mSortOrder = "$DAY  DESC")
        ...
        }
    }

Let me know if ther is a better solution.

Hope that can help.