Reputation: 25
Been trying to solve this Firebase loading arraylist problem for a while now but no idea how to get it solved.
Object Class
public class Book {
private String title;
private String author;
private String ISBN;
private String photo;
private String ownerEmail;
private String ownerID;
private String BookID;
private Date returnDate;
private Status status;
private String borrowerID;
public Book(){}
public Book(String title, String author, String ISBN, String photo, String ownerEmail, String ownerID) {
this.title = title;
this.author = author;
this.ISBN = ISBN;
this.photo = photo;
this.ownerEmail = ownerEmail;
this.ownerID = ownerID;
this.status = Status.Available;
if(this.BookID == null || this.BookID.isEmpty())
this.BookID = UUID.randomUUID().toString();
}
public enum Status{
Available,
Requested,
Accepted,
Borrowed
}
I have getter and setter for all the variables, and what I'm doing is load this information from firebase using the code:
public void loadMyBookFromFirebase(){
final ArrayList<Book> bookList = new ArrayList<>();
DatabaseReference userReference = FirebaseDatabase.getInstance().getReference().child("users").child(this.userID).child("myBooks");
userReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("testing","books" + dataSnapshot.toString());
if(dataSnapshot.exists()) {
try {
for (DataSnapshot books : dataSnapshot.getChildren()) {
Book book = dataSnapshot.getValue(Book.class);
Log.d("testing","books" + book.getAuthor());
//load book into ListView
}
} catch (Exception e){
e.printStackTrace();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w("testing","Error: ", databaseError.toException());
}
});
}
this is my firebase database firebase database
i keep getting a
Can't convert object of type java.util.ArrayList
to type com.example.cmput301w19t15.Book
error on the line Book book = dataSnapshot.getValue(Book.class);
im not sure why i am getting the convert object error, i do not want to search for individual variables and set them, which defeat the purpose of the object class
I would really like some insight on this
Upvotes: 1
Views: 65
Reputation: 138824
To solve this, please change the following line of code:
Book book = dataSnapshot.getValue(Book.class);
to
Book book = books.getValue(Book.class);
You need to get the data from the books
object and not from the dataSnapshot
object.
Upvotes: 1