1

I'm trying to work with Firebase and Lists.

My objects contains a class extending ArrayList such as:

MyClass {
    // other fields here
    public static class List extends ArrayList<Foo> {};
}

If I try to upload a List item to Firebase database, it works out of the box and no problem are faced.

The problem come when I try to retrieve these Lists from the server, such as:

MyClass mMyClass = dataSnapshot.getValue(MyClass.class);

This throws an exception saying

com.google.firebase.database.DatabaseException: Can't convert object of type java.util.ArrayList to type mypackage.MyClass$List

The only possible thing working for me is to revert back to ArrayList<Foo> instead of extending it from another class.

Is there any other possible way to cast without problems? Thanks in advance.

koceeng
  • 2,169
  • 3
  • 16
  • 37
Lampione
  • 1,622
  • 3
  • 21
  • 39

3 Answers3

1

Try using a GenericTypeIndicator to read the list data as a generic collection:

GenericTypeIndicator<MyClass.List> t = new GenericTypeIndicator<MyClass.List>() {};
MyClass.List mList = dataSnapshot.getValue(t);

I'm not sure whether this will work with an inner class. You may need to declare List as its own stand-alone type. See this question for more examples.

Travis Christian
  • 2,412
  • 2
  • 24
  • 41
  • Thank you! Exactly what I was looking for – Lampione Mar 09 '17 at 06:05
  • I'm curious how this worked out for you with your generic list being a member of the class you want to read. I looked for a solution but only found [this unanswered question.](http://stackoverflow.com/q/41948309/213156) – Travis Christian Mar 09 '17 at 15:39
0

Did you try getting the value as ArrayList and then casting it to your class. Something like:

MyClass mMyClass = (MyClass) dataSnapshot.getValue(ArrayList.class);

Hristo Stoyanov
  • 1,960
  • 1
  • 12
  • 24
  • My problem is that the class 'List' is inside the class which I'm passing to the 'getValue()' method – Lampione Mar 06 '17 at 11:25
0

User addEventValueListener for getting arraylist of particular reference

Chirag.T
  • 746
  • 1
  • 6
  • 18