I\'m having some issues reading from a Firebase Database.
I have a pretty simple layout
{
\"lot\" : {
\"lot1\" : \"low\",
\"lot2\" : \"low\",
I had the same question and this is what i used. Modifying to fit the question here
private List<String> lotList;
lotList = new ArrayList<>();
DatabaseReference reference= database.getInstance().getReference().child("lot");
Now adding value event listener
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> mData = dataSnapshot.getChildren();
for(DataSnapshot d : mData){
String lot_string = d.getValue(String.class);
lotList.add(lot_string);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
you can use typecast to JSONObject
and parse the JSONObject
JSONObject jsonObject= new JSONObject((Map)dataSnapshot.getValue());
JSONObject jsonObj= (JSONObject) jsonObject.get("lot");
for (Object key : jsonObj.keySet()) {
//based on you key types
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
}
if you using java 8 than you use lamada expression.
There's some tweak in your code. Your
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getInstance().getReference();
should be write like this,
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference database = myRef.child("anyValueNameYouSpecifyInConsole");
Those 2 lines should be declare outside onCreate method. The one that you need to specify with addValueEventListener is the 2nd DatabaseReference, not the first one. So, it should looks like this from my example,
database.addValueEventListener (new ValueEventListener)
and it will import method.
If you wish the data to be displayed in a particular TextView, then just findViewById the TextView you wanna use and include it in onDataChange method like so,
String x = dataSnapshot.getValue(String.class);
textViewNameDeclared.setText(x);
And don't forget to change the security rule for reading.