Reputation: 344
I'm trying to get value from the last node on firebase Datasebase
I've seen a few solutions but none of them worked for me.
The code is given below:
setData = FirebaseDatabase.getInstance().getReference().child("Questions");
Query lastQuery = setData.orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("JSON_OBJ")) {
SubmitKey item = dataSnapshot.getValue(SubmitKey.class);
String key2 = item.getJSON_OBJ();
} else {
Snackbar.make(findViewById(R.id.QuestionLayout), "JSON_ObJ not found", Snackbar.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
My Constructor Class
public class SubmitKey {
private String JSON_OBJ;
public SubmitKey() {
}
public SubmitKey(String JSON_OBJ) {
this.JSON_OBJ = JSON_OBJ;
}
public String getJSON_OBJ() {
return JSON_OBJ;
}
}
instead of getting the value it is going to the else statement and showing 'JSON_OBJ not Found'.
Any help would be appreciated.
Edit: I've made some changes in the code and now it is showing no setter/field found for 0-101 found on class submitKey
D/ViewRootImpl@5b51511[Questions]: ViewPostIme pointer 0
D/ViewRootImpl@5b51511[Questions]: ViewPostIme pointer 1
And it is aslo not going inside if statement goes to else statement
Upvotes: 0
Views: 34
Reputation: 600116
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your onDataChange
will need to take care of this list, by iterating over snapshot.getChildren()
:
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()) {
if (dataSnapshot.hasChild("JSON_OBJ")) {
SubmitKey item = dataSnapshot.getValue(SubmitKey.class);
String key2 = item.getJSON_OBJ();
} else {
Snackbar.make(findViewById(R.id.QuestionLayout), "JSON_ObJ not found", Snackbar.LENGTH_LONG).show();
}
}
}
Upvotes: 1