遇到数据库处理问题导致应用崩溃(Kotlin)

huangapple go评论65阅读模式
英文:

Having problem with database handler crushes the app (kotlin)

问题

It seems like you're encountering an issue with the dbHandler property not being initialized before it's being used in your shopping_list fragment. To resolve this, you need to ensure that the dbHandler is properly initialized before you use it in your fragment. Here's the modified code with the necessary changes:

In your shopping_list fragment:

class shopping_list : Fragment() {

    lateinit var dbHandler: DBHandler

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Initialize the dbHandler here
        dbHandler = DBHandler(requireContext())

        // ... (rest of your code)

        return view
    }

    // ... (rest of your code)
}

By adding the line dbHandler = DBHandler(requireContext()), you ensure that the dbHandler is properly initialized with the appropriate context before you use it in the fragment.

Additionally, it looks like there's a typo in your code for accessing the context. Replace getContext() with requireContext():

val dialog = AlertDialog.Builder(requireContext())

And:

val tempView = layoutInflater.inflate(R.layout.dialog_shoppinglist, null)

After making these changes, your app should properly initialize the dbHandler and hopefully resolve the issue you're facing.

英文:

I am creating app that allows use to add items to a list inside fragment.
now every time the compiler reach to the database handler calling function the app crush and i cant find the reason.
shopping_list.kt

package com.example.pricetag.fragments

import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.example.pricetag.R
import com.example.pricetag.fragments.DTO.ItemList
import kotlinx.android.synthetic.main.fragment_shopping_list.*

class shopping_list : Fragment() {

    lateinit var dbHandler: DBHandler

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        var view = inflater.inflate(R.layout.fragment_shopping_list, container, false)
        val addItem_button = view.findViewById<com.google.android.material.floatingactionbutton.FloatingActionButton>(R.id.fab_shoppiglist)
        addItem_button.setOnClickListener {
            val dialog = AlertDialog.Builder(getContext())
            val tempView = layoutInflater.inflate(R.layout.dialog_shoppinglist,null)
            val text_result = tempView.findViewById<EditText>(R.id.et_Itemlist)
            dialog.setView(tempView)
            dialog.setPositiveButton("Add") { _: DialogInterface, _: Int ->
                if (text_result.text.isNotEmpty()) {
                    val itemList = ItemList()
                    itemList.name = text_result.text.toString()
                    dbHandler.addItem(itemList)
                }
            }
            dialog.setNegativeButton("Cancel"){ _: DialogInterface, _: Int->

            }
            dialog.show()
        }

        return view
    }

    private fun refreshList(){
        rv_shoppinglist.adapter = ShoppinglistAdpter(this.requireContext(),dbHandler.getItem())
    }


    class ShoppinglistAdpter(val context: Context, val list: MutableList<ItemList>): RecyclerView.Adapter<ShoppinglistAdpter.ViewHolder>(){
        class ViewHolder(v : View) : RecyclerView.ViewHolder(v){
            val itemName : TextView = v.findViewById(R.id.tv_item_name)
        }

        override fun onCreateViewHolder(p0: ViewGroup, pl: Int): ViewHolder {
            return ViewHolder(LayoutInflater.from(context).inflate(R.layout.rv_child_shoppinglist,p0))
        }

        override fun getItemCount(): Int {
            return list.size
        }

        override fun onBindViewHolder(holder: ViewHolder, p1: Int) {
            holder.itemName.text = list[p1].name
        }

    }

}

DBHandler.kt

package com.example.pricetag.fragments

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import com.example.pricetag.fragments.DTO.ItemList

class DBHandler(val context: Context) : SQLiteOpenHelper(context, DB_NAME,null, DB_VERSION){
    override fun onCreate(db: SQLiteDatabase){
        val createItemTable = "CREATE TABLE $TABLE_ITEMS (" +
                "$COL_ID integer PRIMARY KEY AUTOINCREMENT," +
                "$COL_NAME varchar," +
                "$COL_AMOUNT integer);"
        db.execSQL(createItemTable)
    }

    override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {

    }

    fun addItem(itemList : ItemList) : Boolean {
        Log.i("Err","#9")
        val db = writableDatabase
        val cv = ContentValues()
        cv.put(COL_NAME, itemList.name)
        val result = db.insert(TABLE_ITEMS, null, cv)
        return result != (-1).toLong()
    }

    fun getItem() : MutableList<ItemList>{
        val result : MutableList<ItemList> = ArrayList()
        val db : SQLiteDatabase = readableDatabase
        val queryResult = db.rawQuery("SELECT * from $TABLE_ITEMS", null)
        if(queryResult.moveToFirst()){
            do{
                val itemList = ItemList()
                itemList.id = queryResult.getLong(queryResult.getColumnIndex(COL_ID))
                itemList.name = queryResult.getString(queryResult.getColumnIndex(COL_NAME))
                itemList.amount = queryResult.getInt(queryResult.getColumnIndex(COL_AMOUNT))
                result.add(itemList)
            } while(queryResult.moveToNext())
        }

        return result
    }
}

ItemList.kt

package com.example.pricetag.fragments.DTO

class ItemList {
    var id: Long = -1
    var name: String = ""
    var amount = 0


}

Const.kt

package com.example.pricetag.fragments

const val DB_NAME = "ItemList"
const val DB_VERSION = 1
const val TABLE_ITEMS = "Items"
const val COL_ID = "id"
const val COL_NAME = "name"
const val COL_AMOUNT = "amount"

please help me find the problem and ofc the soulution.
appreciate it. have a nice day

edit: this is crush log (Error

2020-08-28 03:42:23.932 6619-6619/com.example.pricetag E/RecyclerView: No adapter attached; skipping layout
2020-08-28 03:42:26.710 6619-6619/com.example.pricetag E/RecyclerView: No adapter attached; skipping layout
2020-08-28 03:42:26.740 6619-6619/com.example.pricetag E/RecyclerView: No adapter attached; skipping layout
2020-08-28 03:42:30.059 6619-6619/com.example.pricetag E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.pricetag, PID: 6619
    kotlin.UninitializedPropertyAccessException: lateinit property dbHandler has not been initialized
        at com.example.pricetag.fragments.shopping_list.getDbHandler(shopping_list.kt:20)
        at com.example.pricetag.fragments.shopping_list$onCreateView$1$1.onClick(shopping_list.kt:38)
        at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6710)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)

and this is crush log (Debug):

2020-08-28 03:42:30.059 6619-6619/com.example.pricetag E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.pricetag, PID: 6619
    kotlin.UninitializedPropertyAccessException: lateinit property dbHandler has not been initialized
        at com.example.pricetag.fragments.shopping_list.getDbHandler(shopping_list.kt:20)
        at com.example.pricetag.fragments.shopping_list$onCreateView$1$1.onClick(shopping_list.kt:38)
        at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6710)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)

答案1

得分: 0

onCreateView(){
...
dbHandler = DBHandler(getActivity())
...
}
英文:

initializing code is not included here.
ex)

onCreateView(){
...
dbHandler = DBHandler(getActivity())
...
}

huangapple
  • 本文由 发表于 2020年8月28日 04:10:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63623520.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定