I'm trying to read from a Firebase Database, I've read and looked everywhere, but I'm at a dead end.
Here's all that I've done.
Dependencies:
implementation 'com.google.firebase:firebase-storage:9.2.1'
implementation 'com.google.firebase:firebase-database:9.2.1'
implementation 'com.google.firebase:firebase-auth:9.2.1'
implementation 'com.google.firebase:firebase-core:9.2.1'
minSdkVersion: 15
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
then in a Button onClick method, I put the listener:
mDatabase.child("List").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String savedData = dataSnapshot.getValue(String.class);
Log.d(TAG, "snapshot: " + savedData);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, "Error");
}
});
Here is a look at the Database.
Would appreciate the input.
You're trying to read a String
value under List
. But right under List
there's no string value, rather there's a list of objects under there. To get the actual values, you'll need to navigate the JSON structure in your code.
Something like:
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("List").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot tierSnapshot: dataSnapshot.getChildren()) {
Log.d(TAG, tierSnapshot.getKey(); // "Tier 1", "Tier 1 B"
for (DataSnapshot secondSnapshot: tierSnapshot.getChildren()) {
Log.d(TAG, secondSnapshot.getKey(); // "Tier 2", "Tier 2 B"
String str = secondSnapshot.getValue(String.class);
Log.d(TAG, str); // null, "2 B"
Long num = secondSnapshot.getValue(long.class);
Log.d(TAG, num); // 2, null
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "Error", databaseError);
}
});
An extra thing to note is that your values are of a different type, with the first one being the number 2
, while the second one is a string "2 B"
. Hence the two getValue()
calls, to get the specific type out of there. You could also just do secondSnapshot.getValue()
and deal with the resulting object as you'd usually do (eg call toString()
on it).
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.