内容提供者:onCreate() 类型不匹配 - 上下文?与上下文(Kotlin)
Content provider: onCreate() type mismatch - Context? vs Context (Kotlin)
我正在尝试在我的内容提供程序中实施 onCreate() 方法,但我想不通应该如何解决此错误:
"Type mismatch: inferred type is Context? but Context was expected
这是我的 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
}
}
和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.")
}
}
我从来没有在 android studio / kotlin 工作过,我想这可能是一个简单的解决方案,但我似乎无法修复它...
您用来创建 databaseHandler 的上下文具有可为 null 的注释。
public final @Nullable Context getContext() {
return mContext;
}
所以您可以通过使 databaseHandler 上下文为空来修复它
class DatabaseHandler(var context: Context?)
或者您可以在实例化数据库处理程序之前添加空检查:
override fun onCreate(): Boolean {
dbHandler = context?.let { DatabaseHandler(it) }
return false
}
context
returns 一个可为空的上下文(Context?
),因为它在 onCreate()
之前的生命周期中为空。根据 the documentation,在 onCreate()
内部,它不再为 null,因此可以安全地使用 !!
.
断言 non-null
此外,如果没有问题,您应该从 onCreate
返回 true
。
override fun onCreate(): Boolean {
dbHandler = DatabaseHandler(context!!)
return true
}
我正在尝试在我的内容提供程序中实施 onCreate() 方法,但我想不通应该如何解决此错误:
"Type mismatch: inferred type is Context? but Context was expected
这是我的 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
}
}
和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.")
}
}
我从来没有在 android studio / kotlin 工作过,我想这可能是一个简单的解决方案,但我似乎无法修复它...
您用来创建 databaseHandler 的上下文具有可为 null 的注释。
public final @Nullable Context getContext() {
return mContext;
}
所以您可以通过使 databaseHandler 上下文为空来修复它
class DatabaseHandler(var context: Context?)
或者您可以在实例化数据库处理程序之前添加空检查:
override fun onCreate(): Boolean {
dbHandler = context?.let { DatabaseHandler(it) }
return false
}
context
returns 一个可为空的上下文(Context?
),因为它在 onCreate()
之前的生命周期中为空。根据 the documentation,在 onCreate()
内部,它不再为 null,因此可以安全地使用 !!
.
此外,如果没有问题,您应该从 onCreate
返回 true
。
override fun onCreate(): Boolean {
dbHandler = DatabaseHandler(context!!)
return true
}