7

I want to get HashMap<String?, String?>? from firebaseDatabase:

override fun onDataChange(dataSnapshot: DataSnapshot) {
    val users: HashMap<String?, String?>? = dataSnapshot.value as HashMap<String?, String?>?  // todo !!!
    if (users != null) {
        if (!users.containsKey(userUid)) {
            users[userUid] = userName
        }
    }
}

This code works but Android Studio shows a warning on a 2nd line:

 Unchecked cast: Any? to HashMap<String?, String?>?

How to fix this in a proper way?

6
  • 1
    and whats type of dataSnapshot.value? Commented Mar 10, 2018 at 12:42
  • 2
    maybe use getValue(GenericTypeIndicator<T> t) Commented Mar 10, 2018 at 12:42
  • @AntonKazakov it's "Any?" Commented Mar 10, 2018 at 12:47
  • 1
    @Rainmaker so what's wrong?:) you can use suppress warning for unchecked cast. And btw you can omit : HashMap<String?, String?>? Commented Mar 10, 2018 at 12:48
  • @AntonKazakov I'd like to implement it in a safe way. What if someone changes data in firebase. I tried to check if it is Hashmap<String, String> but it doesn't work too Commented Mar 10, 2018 at 13:07

2 Answers 2

7

You can use @Suppress("UNCHECKED_CAST")

(eg)

@Suppress("UNCHECKED_CAST")
val users: HashMap<String?, String?>? = dataSnapshot.value as HashMap<String?, String?>?
Sign up to request clarification or add additional context in comments.

Comments

6

The approach with GenericTypeIndicator works, thank you @leoderprofi

    val ti = object : GenericTypeIndicator<HashMap<String?, String?>?>() {}
    //...
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        val users: HashMap<String?, String?>? = dataSnapshot.getValue(ti)
        if (users != null) {
            if (!users.containsKey(userUid)) {
                users[userUid] = userName
            }
        }
    }

1 Comment

Where is from the GenericTypeIndicator?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.