首页 > 解决方案 > Cannot solve this error. Kotlin -Firebase

问题描述

I need to get those data to a recyclerview, so I created an adapter class and items class. There's no issues. but this is the error I got:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.busconductor/com.example.busconductor.busCodesActivity}: kotlin.UninitializedPropertyAccessException: lateinit property reference has not been initialized

error

I did all right, but cannot solve this.

Data Class

This's firebase node

This's the code

class busCodesActivity : AppCompatActivity() {

    private lateinit var reference : FirebaseDatabase1

    private lateinit var codeRecyclerView: RecyclerView
    private lateinit var codeArrayList: ArrayList<CityCodes>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bus_codes)


        codeRecyclerView = findViewById(R.id.recyclerView)
        codeRecyclerView.layoutManager = LinearLayoutManager(this)
        codeRecyclerView.setHasFixedSize(true)
        codeArrayList = arrayListOf<CityCodes>()
        getCodeDetails()

        val Button = findViewById<Button>(R.id.button5)
        Button.setOnClickListener {
            startActivity(Intent(this@busCodesActivity, conductorMenu::class.java))}
    }

    private fun getCodeDetails() {
        val ref = reference.getReference("CityCodes")

        ref.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()){
                    for (routeSnapshot in snapshot.children){
                        val code = routeSnapshot.getValue(CityCodes::class.java)
                        codeArrayList.add(code!!)
                    }
                    codeRecyclerView.adapter = CityAdapter(codeArrayList)
                }
            }

            override fun onCancelled(error: DatabaseError) {
                TODO("Not yet implemented")
            }


        })
    }
}

Please help me. I'm new to kotlin.

标签: androidkotlinfirebase-realtime-database

解决方案


As the error message says, you never initialize reference that you declared here:

private lateinit var reference : FirebaseDatabase1

The 1 in FirebaseDatabase1 is unexpected, but I'm going to assume you know where that comes from. If not, you probably want it to be FirebaseDatabase without the 1.

My guess is that you want to initialize that in onCreate to point to the database:

reference = Firebase.database

推荐阅读