简体   繁体   中英

How can I retrieve an object from the Firebase RealTime Database if it contains a List?

I'm trying to learn how to use Firebase, and decided to make a simple android application that uses the Firebase RealTime Database. The game requires a host who hosts a lobby, and players who can join that lobby. I made a host class that has a bunch of data types, among which is a list (the game involves using hints given to players by the host). I'm running into problems when I try to read from the database.

My lobby is a listview that I want to populate with a list of hosts in the database, but when I try to read from it I get this nasty error:

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

I know that there are other questions about the same error, but I couldn't apply those answers with much success. I'm quite new to android development and would greatly appreciate any help.

Here is my user-defined class:

public class HostPlayer {

    private String hostName;
    private String photoUrl;
    private String primaryHint;
    List<String> hints = new ArrayList<String>();
    private int numHints;
    private int numTime;
    private boolean inProgress = false;

    public HostPlayer() {

    }

    public HostPlayer(String hostName, int numHints, int numTime, List<String> hints, String primaryHint, String photoUrl) {
        this.hostName = hostName;
        this.numHints = numHints;
        this.numTime = numTime;
        this.hints = hints;
        this.primaryHint = primaryHint;
        this.photoUrl = photoUrl;
        this.inProgress = false;
    }

    public void setPhotoUrl(String photoUrl) {this.photoUrl = photoUrl;}

    public void setPrimaryHint(String primaryHint) {this.primaryHint = primaryHint;}

    public void setHints(List hints) {this.hints = hints;}

    public String getHostName() {return this.hostName;}

    public int getNumHints() {return this.numHints;}

    public  int getNumTime() {return this.numTime;}

    public String getPrimaryHint() {return this.primaryHint;}

    public List getHints() {return this.hints;}

    public void setInProgress() {this.inProgress = true;}

    public boolean getInProgress() {return this.inProgress;}
}

Here is my code where I read from the database:

public class JoinGame extends AppCompatActivity {

    ListView lv;

    private FirebaseDatabase pFireBaseDatabase;
    private DatabaseReference pDatabaseReference;
    private ChildEventListener pChildEventListener;

    List<HostPlayer> hostPlayerList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_join_game);

        pFireBaseDatabase = FirebaseDatabase.getInstance();
        pDatabaseReference = pFireBaseDatabase.getReference().child("hosts");

        pChildEventListener = new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                HostPlayer hostPlayer = snapshot.getValue(HostPlayer.class); //this is where the error happens
                hostPlayerList.add(hostPlayer);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        };
        pDatabaseReference.addChildEventListener(pChildEventListener);

        lv = findViewById(R.id.listView_hosts);

        ArrayAdapter<HostPlayer> hostPlayerArrayAdapter = new ArrayAdapter<HostPlayer>(
                this, android.R.layout.simple_list_item_1, hostPlayerList
        );//making an arrayAdapter out of the list of HostPlayer objects

        lv.setAdapter(hostPlayerArrayAdapter);
    }
}

This is what the database JSON is structured like:

{
  "hosts" : {
    "some-data-key" : {
      "hints" : [ "first hint", "second hint" ],
      "hostName" : "mom",
      "inProgress" : false,
      "numHints" : 3,
      "numTime" : 30,
      "primaryHint" : "Living Room"
    }
  },
  "players" : {
    "another-data-key" : {
      "hostName" : "firstName",
      "inProgress" : false,
      "numHints" : 0,
      "numTime" : 0
    }
  }
}

I understand that the list "hints" is causing this error, but still don't understand why and how I can fix it. I would greatly appreciate any explanations and/or solutions. Thanks for your time and help.

Edit: I forgot to paste the logcat, here it is:

2021-10-23 16:11:20.732 21137-21137/com.example.treasurehunt E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.treasurehunt, PID: 21137
    com.google.firebase.database.DatabaseException: Class java.util.List has generic type parameters, please use GenericTypeIndicator instead
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:224)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(CustomClassMapper.java:179)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$100(CustomClassMapper.java:48)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(CustomClassMapper.java:593)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(CustomClassMapper.java:563)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:433)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80)
        at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
        at com.example.treasurehunt.JoinGame$1.onChildAdded(JoinGame.java:41)
        at com.google.firebase.database.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:79)
        at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

One way of doing it might look like this;

public class HostPlayer {

    ...
    List<String> hints = new ArrayList<String>();

    ...

    @Exclude //We are hiding this method from Firebase because we are gonna handle it manually.
    public void setHints(List<String> hints) {this.hints = hints;}
}

and

    pChildEventListener = new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
            // This must be error-free now but the hints list will be missing. We are gonna add them manually.
            // (All fields except "hintsList" will be set automatically.)
            HostPlayer hostPlayer = snapshot.getValue(HostPlayer.class);

            // We have the HostPlayer's snapshot. And we need the "hints" list which is one of its children.
            DataSnapshot hintsSnapshot = dataSnapshot.child("hints");
            
            
            // Iterate through the snapshot and add the hints to the list.
            List<String> hintsList = new ArrayList<>();
            for (DataSnapshot currentHint : hintsSnapshot.getChildren()) {
                String hint = currentHint.getValue();
                hintsList.add(hint);
            }

            hostPlayer.setHints(hintsList);//We have the host player with the hintsList!
            ...
        }
        ...
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM