I am trying to implement the onCreate() method in my Content provider and can't wrap my head around what I should do to resolve this error:
"Type mismatch: inferred type is Context? but Context was expected
Here is my DatabaseHandler.kt
package com.example.rewardreacher
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.widget.Toast
const val DATABASE_NAME = "GoalDB"
const val TABLE_NAME = "Goals"
const val COL_NAME = "name"
const val COL_FREQUENCY = "frequency"
const val COL_PERFORMED = "performed"
const val COL_ID = "id"
class DatabaseHandler(var context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, 1) {
override fun onCreate(db: SQLiteDatabase?) {
// No DB - Then create
val createTable = "CREATE TABLE $TABLE_NAME ("
"$COL_ID INTEGER PRIMARY KEY AUTOINCREMENT,"
"$COL_NAME VARCHAR(256), "
"$COL_FREQUENCY INTEGER(1), "
"$COL_PERFORMED INTEGER(256))"
db?.execSQL(createTable)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
db?.execSQL("DROP TABLE IF EXISTS $DATABASE_NAME");
onCreate(db);
}
fun insertData(goal : Goal) {
val db = this.writableDatabase
val cv = ContentValues()
cv.put(COL_NAME, goal.name)
cv.put(COL_FREQUENCY, goal.frequency)
cv.put(COL_PERFORMED, goal.performed)
val result = db.insert(TABLE_NAME, null, cv)
if (result == (0).toLong())
Toast.makeText(context, "Failed", Toast.LENGTH_LONG).show()
else
Toast.makeText(context, "Success", Toast.LENGTH_LONG).show()
}
@SuppressLint("Range")
fun readData() : MutableList<Goal> {
val list: MutableList<Goal> = ArrayList()
val db = this.readableDatabase
val query = "Select * from $TABLE_NAME"
val result = db.rawQuery(query, null)
if (result.moveToFirst()) {
do {
val goal = Goal()
goal.id = result.getString(result.getColumnIndex(COL_ID)).toInt()
goal.name = result.getString(result.getColumnIndex(COL_NAME))
goal.frequency = result.getString(result.getColumnIndex(COL_FREQUENCY)).toInt()
goal.performed = result.getString(result.getColumnIndex(COL_PERFORMED)).toInt()
list.add(goal)
} while (result.moveToNext())
}
result.close()
db.close()
return list
}
}
And MyContentProvider.kt
package com.example.rewardreacher.provider
import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import com.example.rewardreacher.DatabaseHandler
const val DATABASE_NAME = "GoalDB"
const val GOALS_TABLE = "Goals"
const val COL_NAME = "name"
const val COL_FREQUENCY = "frequency"
const val COL_PERFORMED = "performed"
const val COL_ID = "id"
class MyContentProvider : ContentProvider() {
private var dbHandler: DatabaseHandler? = null
override fun onCreate(): Boolean {
dbHandler = DatabaseHandler(context)
return false
}
private val GOALS = 1
private val GOALS_ID = 2
private val sURIMatcher = UriMatcher(UriMatcher.NO_MATCH)
init {
sURIMatcher.addURI(AUTHORITY, GOALS_TABLE, GOALS)
sURIMatcher.addURI(AUTHORITY, GOALS_TABLE "/#",
GOALS_ID)
}
companion object {
val AUTHORITY = "com.example.rewardreacher.provider.MyContentProvider"
val CONTENT_URI : Uri = Uri.parse("content://" AUTHORITY "/"
GOALS_TABLE)
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
TODO("Implement this to handle requests to delete one or more rows")
}
override fun getType(uri: Uri): String? {
TODO(
"Implement this to handle requests for the MIME type of the data"
"at the given URI"
)
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
TODO("Implement this to handle requests to insert a new row.")
}
override fun query(
uri: Uri, projection: Array<String>?, selection: String?,
selectionArgs: Array<String>?, sortOrder: String?
): Cursor? {
TODO("Implement this to handle query requests from clients.")
}
override fun update(
uri: Uri, values: ContentValues?, selection: String?,
selectionArgs: Array<String>?
): Int {
TODO("Implement this to handle requests to update one or more rows.")
}
}
I never work in android studio / kotlin and I guess it is probably a simple solution but I can't seem to fix it...
CodePudding user response:
context
returns a nullable Context (a Context?
) because it's null in the lifecycle before onCreate()
. According to the documentation, inside onCreate()
, it is no longer null, so it is safe to assert non-null with !!
.
Also, you should be returning true
from onCreate
if there wasn't a problem.
override fun onCreate(): Boolean {
dbHandler = DatabaseHandler(context!!)
return true
}
CodePudding user response:
The context that you use to create databaseHandler has a nullable annotation.
public final @Nullable Context getContext() {
return mContext;
}
So you can fix it by making the databaseHandler context nullable
class DatabaseHandler(var context: Context?)
Or you can add a null check before instantiating the databaseHandler :
override fun onCreate(): Boolean {
dbHandler = context?.let { DatabaseHandler(it) }
return false
}