Android Firebase retrieve value - android

I'm trying to get a value from the Firebase.
I am using this piece of code to get that, but all the methods I call on score1 return null.
private void onSignedInInitialize(String username) {
mUsername = username;
final DatabaseReference reference = mFirebaseDatabase.getReference();
Query query = reference.child("scores").orderByChild("username").equalTo(mUsername);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
Score scores1 = dataSnapshot.getValue(Score.class);
Log.d(TAG, " scores1 " + scores1 + " datasnapshot to String " + dataSnapshot.getValue().toString());
Log.d(TAG, " user " + scores1.getUsername());
Log.d(TAG, " user " + scores1.getUsername());
scoresTextView.setText(scores1.getScore());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
My Firebase structure looks like this
I used the example in their documentation (with Post class) and also searched on Google but i can't find how I can get the value of scores.
Thank you for your answer.
This is Score class
public class Score {
private String username;
private String score;
public Score() {
}
public Score(String username, String score) {
this.username = username;
this.score = score;
}
public String getUsername() {
return username;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}

As your database image shows, the database nodes that are instances of Score are children of location scores. Update your code as shown below.
A second problem is that the score in the database is an integer, not a String as your Score class expects. You must either update the DB to contain strings or change Score to handle score as an integer. Also, your Score class is missing a setter method for username.
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
if (dataSnapshot.exists()) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Score scores1 = snap.getValue(Score.class);
Log.d(TAG, " scores1 " + scores1 + " datasnapshot to String " + dataSnapshot.getValue().toString());
Log.d(TAG, " user= " + scores1.getUsername());
Log.d(TAG, " score= " + scores1.getScore());
scoresTextView.setText(scores1.getScore());
}
} else {
Log.e(TAG, "onDataChange: NO DATA");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled: " + databaseError.getMessage());
}
});

Related

Android Retrieving Single Value from FireBase-RealTime Database

Answer needed urgently. I'm trying to retrieve a single value school name as marked in the snapshot attached below and populate it to my android spinner from my firebase-database
private class FireBaseConnection{
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference rootRef = database.getReference().child("root");
DatabaseReference reg_schools = rootRef.child("reg_schools");
}
private ArrayList<String> retrieveAllSchools(){
pBar.setMessage("Please Wait..Retrieving Schools...");
pBar.show();
FireBaseConnection fireBaseConnection = new FireBaseConnection();
String key = fireBaseConnection.reg_schools.push().getKey();
fireBaseConnection.reg_schools.child(key).child("school_name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
resultProcessorObject = snapshot.getValue(SchoolObject.class);
schools_retrieved = resultProcessorObject.getSchool_name();
schools.add( schools_retrieved);
//schools = (ArrayList<Object>) snapshot.getValue();
// Toast.makeText(Main2Activity.this, "Schools are : " + schools, Toast.LENGTH_SHORT).show();
}
Toast.makeText(Main2Activity.this, "Schools are : " + schools, Toast.LENGTH_SHORT).show();
pBar.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return schools;
}
So I want to answer my question..I made it work with the help of #Alex Mamo video
so everything remained unchanged..all i did was tweak my code a bit
Instead of
fireBaseConnection.reg_schools.child(key).child("school_name").addValueEventListener(){
//Then my codes here
}
Instead i did
fireBaseConnection.reg_schools.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
resultProcessorObject = snapshot.child("school_name").getValue(String.class);
//schools_retreived = resultProcessorObject.getSchool_name();
schools.add(resultProcessorObject);
count = dataSnapshot.getChildrenCount();
Toast.makeText(Main2Activity.this, "Total number of " + count + " schools were retreived ", Toast.LENGTH_SHORT).show();
// schools = (ArrayList<Object>) snapshot.getValue();
// Toast.makeText(Main2Activity.this, "Schools are : " + schools, Toast.LENGTH_SHORT).show();
}
Toast.makeText(Main2Activity.this, "Schools are : " + schools, Toast.LENGTH_SHORT).show();
pBar.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
So Basically i used the snapshot to reference the node "school_name" i'm looking for in the onDataChange Method

Query using ValueEventListener

I have just started using Android and Firebase. I have built a simple test Firebase database and I want to run a simple query.
If I use ChildEventListener, I get reasonable results and code for that looks like this:-
Query query = databaseReference.orderByChild("calendarGroup").equalTo("2");
mChildEventListner = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
CalendarEntry calendarEntry = dataSnapshot.getValue(CalendarEntry.class);
linesToDisplay = linesToDisplay + "\n" + calendarEntry.getCalendarDate() +
", " + calendarEntry.getCalendarEntry() +
", " + calendarEntry.getCalendarGroup();
resultText.setText(linesToDisplay);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast mToast = Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT);
mToast.show();
;
}
};
query.addChildEventListener(mChildEventListner);
But as this is a single event query, I wanted to do that using SingleValueListener. It doesn't work (I get null values), The code is below:-
Query query = databaseReference.orderByChild("calendarGroup").equalTo("2");
ValueEventListener mValueEventListener;
mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
CalendarEntry calendarEntry = dataSnapshot.getValue(CalendarEntry.class);
linesToDisplay = linesToDisplay + "\n" + calendarEntry.getCalendarDate() +
", " + calendarEntry.getCalendarEntry() +
", " + calendarEntry.getCalendarGroup();
resultText.setText(linesToDisplay);
}
#Override
public void onCancelled (DatabaseError databaseError){
}
};
query.addListenerForSingleValueEvent(mValueEventListener);
What am I doing wrong?
Please do this:
mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data : dataSnapshot.getChildren()){
CalendarEntry calendarEntry = data.getValue(CalendarEntry.class);
linesToDisplay = linesToDisplay + "\n" + calendarEntry.getCalendarDate() +
", " + calendarEntry.getCalendarEntry() +
", " + calendarEntry.getCalendarGroup();
resultText.setText(linesToDisplay);
}
}
#Override
public void onCancelled (DatabaseError databaseError){
}
};
query.addListenerForSingleValueEvent(mValueEventListener);
Please add the for loop to be able to retrieve the data.
In ValueEventListener you have to loop inside the node which is different that the childeventlistener where it is able to get the values without looping.

I have the following firebase database and i am not able to retrieve the details like name,address,no

The following is an image from firebase database and i am not able to retrieve the data.
MainActivity.java
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
FirebaseData pg=dataSnapshot.getValue(FirebaseData.class);
Log.d(TAG, "Value is: " + value);
Toast.makeText(MainActivity.this,value,Toast.LENGTH_SHORT).show();
}
FirebaseData.java class
public class FirebaseData {
public String name;
public String address;
public String pgid;
public String contact_no;
public FirebaseData() {
// Needed for Firebase
}
public FirebaseData(String address, String name, String contact_no) {
this.name = name;
this.address = address;
this.contact_no=contact_no;
}
To get the address, contact_no and the name from HSRLayout node please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference HSRLayoutRef = rootRef.child("cities").child("Bangalore").child("localities").child("HSRLayout");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String address = dataSnapshot.child("1").child("address").getValue(String.class);
String contact_no = dataSnapshot.child("1").child("contact_no").getValue(String.class);
String name = dataSnapshot.child("1").child("name").getValue(String.class);
Log.d("TAG", address + " / " + contact_no + " / " + name);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
HSRLayoutRef.addListenerForSingleValueEvent(eventListener);
Your output will be:
das / 15615446484 / HSR
If you want to get the data from multiple childs, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference HSRLayoutRef = rootRef.child("cities").child("Bangalore").child("localities").child("HSRLayout");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String address = ds.child("address").getValue(String.class);
String contact_no = ds.child("contact_no").getValue(String.class);
String name = ds.child("name").getValue(String.class);
Log.d("TAG", address + " / " + contact_no + " / " + name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
HSRLayoutRef.addListenerForSingleValueEvent(eventListener);
In Database check Rules and set
{ "rules": {
".read": true,
".write": true}}

How to retrieve particular data from firebase?

While retrieving the data I am using this code
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
Firebasemodel firebasemodel = data.getValue(Firebasemodel.class);
firebasemodels.add(firebasemodel);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});`
This code snippet which returns the complete data of firebase database.
But I want to retrieve the complete data of particular users. How do I achieve it?
Thanks in advance
Try code below:
FirebaseDatabase.getInstance().getReference().child("notepad-secure/notepad").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
while (dataSnapshots.hasNext()) {
user = dataSnapshotChild.getValue(User.class);
users_list.add(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Error", "---" + databaseError.getMessage());
}
});
Model class:
public class User {
public String id;
public String note;
public String tittle;
public User() {
}
public User(String id, String note, String tittle) {
this.id= id;
this.note= note;
this.tittle= tittle;
}
}
And Declare
List<User> users_list;
User user;
Please use this code for getting all data:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference notepadRef = rootRef.child("notepad-secure").child("notepad");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String id = ds.child("id").getValue(String.class);
String note = ds.child("note").getValue(String.class);
String title = ds.child("title").getValue(String.class);
String user = ds.child("user").getValue(String.class);
Log.d("TAG", id + " / " + note + " / " + title + " / " + users);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
notepadRef.addListenerForSingleValueEvent(eventListener);
And your output will be:
-Kono2LMSe... / sadsad / sadsad / NK46X......
If you want to retrieve only specific data, please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference notepadRef = rootRef.child("notepad-secure").child("notepad").child("NK46...");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String id = ds.child("id").getValue(String.class);
String note = ds.child("note").getValue(String.class);
String title = ds.child("title").getValue(String.class);
String user = ds.child("user").getValue(String.class);
Log.d("TAG", id + " / " + note + " / " + title + " / " + users);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
notepadRef.addListenerForSingleValueEvent(eventListener);
It will work for sure.

Sorting in ascending order not working Firebase

Hey I am trying to sort my data in ascending order but the data is getting displayed in the order of how they are stored in the database:
This is the function being used to sort the data to find the least time.
private void getTimeTaken1(final String name) {
final DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference().child("users");
final Query query = databaseReference1.orderByChild("timeTaken").limitToLast(10);
Log.e(TAG, "getTimeTaken1: " + name);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int rank = 1;
for (DataSnapshot userAnswerSnapshot : dataSnapshot.getChildren()) {
if (yourTimeArraylist.size() < 10) {
if (userAnswerSnapshot.child("questions").child(name).hasChild("timeTaken")
&& userAnswerSnapshot.child("questions").child(name).child("checkAnswerCorrect").getValue(String.class).equals("1")) {
Log.e("", "User " + " " + userAnswerSnapshot.child("questions").child(name).child("timeTaken").getValue().toString());
yourTimeArraylist.add(new PreviousDayRank(userAnswerSnapshot.child("random").getValue(String.class),
userAnswerSnapshot.child("name").getValue(String.class),
timetaken(userAnswerSnapshot.child("questions").child(name).child("timeTaken").getValue(Integer.class)),
rank));
Log.e("", "onDataChange: user" + userAnswerSnapshot.child("questions").child(name).child("timeTaken").getValue());
rank++;
} else {
yourTimeArraylist.add(new PreviousDayRank(userAnswerSnapshot.child("random").getValue(String.class), userAnswerSnapshot.child("name").getValue(String.class), "-", rankl̥));
rank++;
}
}
}
query.removeEventListener(this);
databaseReference1.removeEventListener(this);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Your DatabaseReference is wrong. Please use this code:
final DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference().child("users").child(userId).child("questions").child(questionNumber);
final Query query = databaseReference1.orderByChild("timeTaken").limitToLast(10);
Where userId and questionNumber are the id's generated by push() method and the second by you.
Hope it helps.

Categories

Resources