ronnieotieno
ronnieotieno

Reputation: 144

Why is the following function returning null ArrayList?

I have even used List but still, I get null pointer but if I use livedata it updates successfully inside the for a loop. It doesn't return null. Why is it only list or Arraylist which returns null

  fun List(): ArrayList<Bank> {
    val banklist = ArrayList<Bank>()
    val reference = FirebaseDatabase.getInstance().reference
        .child("groups")
        .child(group.group_id)
        .child("financials")
        .child("cash")
        .child("bank")
    reference.addValueEventListener(object : ValueEventListener {

        override fun onCancelled(p0: DatabaseError) {

        }

        override fun onDataChange(dataSnapshot: DataSnapshot) {

            for (singleSnapshot in dataSnapshot.children) {
                Log.d(
                    "Data", "banks found: "
                            + singleSnapshot.value
                )
                val bank = singleSnapshot.getValue(Bank::class.java)
                banklist.add(bank!!)

               bankListLivedata.value = banklist //updates perfectly

            }


            Log.d(
                "Data", "banksList1 ${banklist[0].bank_account} "//This is printing in the log

            )

        }
    }
    )
    Log.d(
        "Data", "banksList2 ${banklist[0].bank_account} " //This is throwing null pointer exception

    )

    return banklist //this is null

  //if I return banklistLivedata it works perfectly and doesn't throw null
}

Upvotes: 0

Views: 944

Answers (2)

smac89
smac89

Reputation: 43098

The solution is to make sure that you are checking if the list is empty before attempting to log, or better yet use one of Kotlin's utility methods (like firstOrNull()) to retrieve the first element of the list:

Log.d("Data", "banksList2 ${banklist.firstOrNull()?.bank_account} ")

I'd also suggest doing the same for the logging inside the listener:

Log.d("Data", "banksList1 ${banklist.firstOrNull()?.bank_account} ")

Upvotes: 0

Neo
Neo

Reputation: 2039

The NPE thrown in your logging is because banklist is modified in a change listener.

Log.d(
        "Data", "banksList2 ${banklist[0].bank_account} " //This is throwing null pointer exception

    )

When no change was done, or inside the listener the iterable dataSnapshot.children is empty - banklist stays empty. So when you call list[index] it will return null since nothing was found and it will throw a NPE because you call .bank_account on null.


return banklist //this is null

I'm pretty sure that banklist at the end of your method is not null. The part is just never reached because the code before throws an Exception.

Upvotes: 2

Related Questions