我尝试在this之后将数据添加到SQLite。但是,添加数据时得到null
DatabaseHandler.kt
override fun onCreate(db: SQLiteDatabase) {
val CREATE_TABLE = "CREATE TABLE $TABLE_NAME (" +
ID + " INTEGER PRIMARY KEY," +
NAME + " TEXT," + DESC + " TEXT," +
COMPLETED + " TEXT);"
db.execSQL(CREATE_TABLE)
}
fun addTask(validasi: Validasi): Boolean {
val db = this.writableDatabase
val values = ContentValues()
values.put(NAME, validasi.name)
values.put(DESC, validasi.desc)
val _success = db.insert(TABLE_NAME, null, values)
db.close()
return (Integer.parseInt("$_success") != -1)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
val DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME
db.execSQL(DROP_TABLE)
onCreate(db)
}
companion object {
private val DB_VERSION = 1
private val DB_NAME = "MyTasks"
private val TABLE_NAME = "Tasks"
private val ID = "Id"
private val NAME = "Name"
private val DESC = "Desc"
private val COMPLETED = "Completed"
}
ResultActivity.kt
class ResultActivity : AppCompatActivity() {
var dbHandler: DatabaseHandler? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_result)
button_save.setOnClickListener(){
var success: Boolean = false
val validasi: Validasi = Validasi()
validasi.name = "1"
validasi.desc = "1"
validasi.completed = "y"
Toast.makeText(this@ResultActivity, ""+validasi.name, Toast.LENGTH_SHORT).show()
success = dbHandler?.addTask(validasi) as Boolean
if (success)
finish()
}
}
但是当我单击按钮时,应用程序已停止并且日志显示为
FATAL EXCEPTION: main
Process: com.wahanaartha.supervisionline, PID: 930
kotlin.TypeCastException: null cannot be cast to non-null type kotlin.Boolean
at ResultActivity
在此行上发生的情况:success = dbHandler?.addTask(validasi) as Boolean
答案 0 :(得分:2)
您永远不会初始化dbHandler
-调用该方法时为null。空安全调用会阻止NPE,但我假设您只是忘记了对其进行初始化。
如果没有,但是您想知道错误本身,则首先需要了解它的作用:
dbHandler?. // if dbHandler != null
addTask(validasi) // call method
as Boolean // and cast as non-null bool
现在,如果您不使用可为空的调用,那会很好。因为dbHandler
从未初始化,所以表达式等效于:
null as Boolean
您不能将null强制转换为非null类型。将其更改为Boolean?
将使其运行,但是您还必须将if语句更改为显式的if(success == true)
。
您应该以任何一种方式进行;但是初始化dbHandler
会起到很多作用。如果您未使用onCreate
方法对其进行初始化,则可以将其设置为lateinit var
,也可以使用非null类型。
答案 1 :(得分:0)
似乎您没有初始化dbHandler
的主要问题。因此,它为null。
将其初始化,例如在onCreate
方法内部。更好的方法是注入依赖项。
根据您的情况,您可以尝试
fun initDependencies() {
dbHandler = DatabaseHandler(this@ResultActivity);
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_result)
initDependencies();
button_save.setOnClickListener(){
var success: Boolean = false
val validasi: Validasi = Validasi()
validasi.name = "1"
validasi.desc = "1"
validasi.completed = "y"
Toast.makeText(this@ResultActivity, ""+validasi.name, Toast.LENGTH_SHORT).show()
success = dbHandler?.addTask(validasi) as Boolean
if (success)
finish()
}
}
尝试一下,它应该可以工作。当然,如果您有构造函数参数,则应在创建DatabaseHandler
实例时提供它们。
还请阅读Zoe
的答案,其中包含需要理解的重要信息。在编写应用程序之前,您最好学习基本的语言结构和AndroidSDK基础结构。