RAnjeet PApa
RAnjeet PApa

Reputation: 23

Kotlin Null pointer exception

I'm trying to display emails of users stored in firebase database. I've this below code

    snapsListView = findViewById(R.id.snapsList)
    val adapter = emails?.let { ArrayAdapter(this, android.R.layout.simple_list_item_1, it) }
    snapsListView?.adapter = adapter

    auth.currentUser?.uid?.let { FirebaseDatabase.getInstance().getReference().child("users").child(it).child("snaps").addChildEventListener(object: ChildEventListener{
        override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) {
            emails?.add(snapshot.child("from").value as String)

            adapter?.notifyDataSetChanged()
            try {
                for(x in emails!!){
                    Log.i("Emails", x)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

Emails are present in the database and as per the hierrarchy also, users-> uid->snaps and snaps contains the email in "from"

Don't know what is causing this error, or how do i resolve this.

Always getting null pointer exception

Upvotes: 0

Views: 201

Answers (1)

Iaroslav Postovalov
Iaroslav Postovalov

Reputation: 2453

By using !! operator you have asserted that emails is not null. However, Kotlin thrown runtime exception because emails is null actually. Consider replacing !! with safe-access:

emails?.let { for (x in it) Log.i("Emails", x) }

Upvotes: 3

Related Questions