Search code examples
androidfirebasefirebase-realtime-databasepojo

Firebase POJO not working, not recognizing class that I am try to cast to


When I run the code below, I get the following error:

com.google.firebase.database.DatabaseException: Class java.util.HashMap has generic type parameters, please use GenericTypeIndicator instead.

seniorRef.orderByChild("seniorID").equalTo(caretaker.getSeniorID())
    .addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot data : dataSnapshot.getChildren()) {

                Log.d("senior", data.toString());
                Senior senior = data.getValue(Senior.class);
                seniorBox.setText(senior.getFirstName() + " " + senior.getLastName());
                caretasks(senior);
            }
        }

What's weird is that this code was working perfectly for a very long time and I made minor changes to the Senior class (below) for stuff that I am currently working on. It was working when I made some progress last night but now it refuses to convert it from a HashMap to Senior. If I try casting it as (Senior) data.getValue(), it throws a type conversion error. Please let me know what I am doing wrong.

public class Senior implements Serializable {

private String seniorID;
private String firstName;
private String lastName;
private String address;
private HashMap<String, HashMap> activities;

public Senior (){}

...

}

Edit: It's also worth mentioning that I have another class that makes the exact same query on the same object, which works just fine.


Solution

  • This is happening because your HashMap does not have generic type parameters. The <String, Object> are missing. So in order to solve this, you need to change this line:

    private HashMap<String, HashMap> activities;
    

    with this line:

    private Map<String, Map<String, Object>> activities;
    

    And now you can get the data accordingly.

    Hope it helps.