How To Get String Array From Firebase Realtime Database
databaseReference = FirebaseDatabase.getInstance().getReference('/sample'); databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDat
Solution 1:
To retrieve values separately, you can use a code like this:
databaseReference.child("category").addValueEventListener(newValueEventListener() {
@OverridepublicvoidonDataChange(@NonNull DataSnapshot dataSnapshot) {
for (int i=0;i<3;i++) {
// category is an ArrayList you can declare above
category.add(dataSnapshot.child(String.valueOf(i)).getValue(String.class));
}
@OverridepublicvoidonCancelled(@NonNull DatabaseError databaseError) { // Do something for this
}
});
Similarly you can add values of other nodes in your other ArrayLists, just by changing the value of Childs in this code.
Solution 2:
Firebase has no native support for arrays. If you store an array, it really gets stored as an "object" with integers as the key names.
// we send this
['hello', 'world']
// Firebase stores this
{0: 'hello', 1: 'world'}
Best Practices: Arrays in Firebase
// TRY THIS
@OverridepublicvoidonDataChange(@NonNull DataSnapshot dataSnapshot) {
youNameArray = newArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String data = snapshot.getValue(String.class);
youNameArray.add(data);
}
Log.v("asdf", "First data : " + youNameArray.get(0));
}
Solution 3:
Something like this:
databaseReference = FirebaseDatabase.getInstance().getReference("/sample");
databaseReference.addValueEventListener(newValueEventListener() {
@OverridepublicvoidonDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshotsampleSnapshot: dataSnapshot.getChildren()) {
Log.d(TAG, "onDataChange: sampleSnapshot "+sampleSnapshot.getKey()+" = "+sampleSnapshot.getValue());
}
}
@OverridepublicvoidonCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
The difference is that in my answer I loop over dataSnapshot.getChildren()
to get each individual sample snapshot. The sampleSnapshot.getValue()
call should return a List
.
Solution 4:
FirebaseDatabasedatabase= FirebaseDatabase.getInstance();
DatabaseReferencerefence= database.getReference();
refence.addValueEventListener(newValueEventListener()
{
@OverridepublicvoidonDataChange(DataSnapshot snapshot) {
// TODO Auto-generated method stub
ArrayList array= newArrayList<>();
for (DataSnapshot ds : snapshot.getChildren()){
Stringdata= ds.getValue().toString();
array.add(data);
}
System.out.println(array);
}
@OverridepublicvoidonCancelled(DatabaseError error) {
// TODO Auto-generated method stub
}
});
In my case String.class
does not work instead .toString
method works
Stringdata= ds.getValue().toString();
Post a Comment for "How To Get String Array From Firebase Realtime Database"