2

I have this Firebase:

The code

I'm trying to get all the questions data with this code:

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference questionsRef = database.getReference("questions");

questionsRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {

        HashMap question = dataSnapshot.getValue(HashMap.class);

        System.out.println(question.get("0"));
    }
}

But I get the error:

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

I tried few ways but this is last error. How I can get each question data and all the options of the questions?

AL.
  • 36,815
  • 10
  • 142
  • 281
jtwalters
  • 1,024
  • 7
  • 25

4 Answers4

1

Options looks like a numbered list to me, so don't have to use a Map to get it's contents.

GenericTypeIndicator<List<String>> gti = new GenericTypeIndicator<List<String>>() {};

String question = dataSnapshot.child("question").getValue(String.class);
List<String> questionOptions = dataSnapshot.child("options").getValue(gti);
Linxy
  • 2,525
  • 3
  • 22
  • 37
0

First, you should change question type to Map, not HashMap (like @varjo mentioned)

Second, in your code you get the value is 1 step above where it should be. So it should be like this:

Map<String, String> question = dataSnapshot.child("options").getValue(Map.class);

Hope this helps

EDIT

To get question text, use this:

String questionText = dataSnapshot.child("question").getValue(String.class);

Note: for best practice, I think you should create a custom object that combine the question and options together

Community
  • 1
  • 1
koceeng
  • 2,169
  • 3
  • 16
  • 37
0
Map<String, String> question = dataSnapshot.child("options").getValue(Map.class);

Take Array of this question..

Chirag.T
  • 746
  • 1
  • 6
  • 18
0

"options" is not a map, it is a list or an array. Do something like this

GenericTypeIndicator<List<String>> genericTypeIndicator = new GenericTypeIndicator<List<String>>() {};
List<String> list = dataSnapshot.child("options").getValue(genericTypeIndicator);
VVB
  • 7,363
  • 7
  • 49
  • 83