Java – dataSnapshot.getValue Android Studio Kotlin error

dataSnapshot.getValue Android Studio Kotlin error… here is a solution to the problem.

dataSnapshot.getValue Android Studio Kotlin error

I

converted a java file to a kotlin file in a recent project, the problem is that I get an error while using this code:

 val map = dataSnapshot.getValue<Map<*, *>>(Map<*, *>::class.java)

I have a red line under “Map::class” and Android Studio says:

Only classes are allowed on the left hand side of a class literal

What should I do with this code? Is there any other way to write it?

This is a related kotlin code fragment :

val messageText = messageArea!!. text.toString()
        if (messageText != "") {
            val map = HashMap<String, String>()
            map.put("message", messageText)
            map.put("user", UserDetails.username)
            reference1!!. push().setValue(map)
            reference2!!. push().setValue(map)
            messageArea!!. setText("")
        }
    }
    reference1!!. addChildEventListener(object : ChildEventListener {
        override fun onChildAdded(dataSnapshot: DataSnapshot, s: String) {
            val map = dataSnapshot.getValue<Map<*, *>>(Map<*, *>::class.java)
            val message = map.get("message").toString()
            val userName = map.get("user").toString()

Original Java code fragment

:

String messageText = messageArea.getText().toString();

if(!messageText.equals("")){
                Map<String, String> map = new HashMap<String, String>();
                map.put("message", messageText);
                map.put("user", UserDetails.username);
                reference1.push().setValue(map);
                reference2.push().setValue(map);
                messageArea.setText("");
            }
        }
    });

reference1.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Map map = dataSnapshot.getValue(Map.class);
            String message = map.get("message").toString();
            String userName = map.get("user").toString();

Solution

Try converting it.

val map = dataSnapshot.getValue(Map::class.java) as Map<String, String>

You might want to suppress the “unchecked type conversion” warning, but that’s okay.

Related Problems and Solutions