I am doing a project with firebase, able to save some records on the database, but retrieving it has been an issue for me, I've meddled with other posts from SO but they haven't worked for me. This is how the database looks like (An example):
And my code for retrieving the data:
private void readDataFromDB() {
databaseReference.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = new User();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
user.setStrName(//Get the Name of the user);
user.setStrScore(//Get the Score of the user));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
The User class:
public class User {
String strName, strScore;
public String getStrName() {
return strName;
}
public void setStrName(String strName) {
this.strName = strName;
}
public String getStrScore() {
return strScore;
}
public void setStrScore(String strScore) {
this.strScore = strScore;
}
}
How can I get the name and score from each specific user
In your code, you are setting values, you need to be retrieving values using the getters.
Try the following:
databaseReference.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
String name = user.getStrName();
String score = user.getStrScore();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
But, first you need to add the values to the database example:
User user = new User();
user.setStrName("my_name");
user.setStrScore("20");
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
ref.push().setValue(user);
Note setValue():
In addition, you can set instances of your own class into this location, provided they satisfy the following constraints:
The class must have a default constructor that takes no arguments
The class must define public getters for the properties to be assigned. Properties without a public getter will be set to their default value when an instance is deserialized
You need to add a default constructor to the POJO class public User(){} and also the field names in the class should match the ones in the database. So change this String strName, strScore; into this String name, score; and generate the getters and setters again.
Instead of creating profile in every node you can use a global profile node, and in that store the profile data with their UID, which would make it easier for you to fetch detail of single user.
-profile
-UID1
-name
-score
-UID2
-name
-score
While retrieving you can use getCurrentUser.getUid() to retrieve data for each user:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseReference.child("users").child("profile").child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = new User();
user = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Related
Model Class
public String id;
public String total;
public List<CartModel> orderList;
public String currentDate;
public String orderBy;
I want to fetch these objects but unfortunately can't do this.
I'm accessing this list in my adapter class like the following way but getting null value.
protected void onBindViewHolder(#NonNull final OrderHolder holder, int position, #NonNull Orders model) {
List<CartModel> list = new ArrayList<>();
list = model.getOrderList();
Log.i("Orders", list+"");
holder.dateTime.setText(model.getCurrentDate());
holder.grandTotal.setText("Total "+model.getTotal());
holder.orderBy.setText(model.getOrderBy());
}
Please provide me a valid solution for doing this
The name of your field in the Java code doesn't match the property name in the JSON.
To make them match, change:
public List<CartModel> orderList;
To:
public List<CartModel> orderItems;
String userid="your unique id";
String orderid="your unique id";
DatabaseReference database=FirebaseDatabase.getInstance().getReference()
databse.child("yourroot")
.child("Users")
.child(userid)
.child("Orders")
.child(orderid)
.child("orderItems")
.addValueEventListener(new ValueEventListener {
#Override
void onCancelled(#NonNull DatabaseError error) {
//handle error as per your requirement
}
#Override
void onDataChange(#NonNull DataSnapshot snapshot) {
YourModel model=snapshot.getValue(YourModel.class)
//use the model or add to adapter payload and notify it on mainthread
}
})
Note: you may get DatabaseException if your model class is not an appropriate class to hold values from the DB.
I am trying to retrieve the custom username the user on my app sets for themselves from my Firebase Database. I have some code in place that is functioning properly, but I do not know exactly what to set my TextView equal to in order to get the data the code is retrieving.
So here is the method that goes and gets the username from my Firebase Database.
public void getUser(final MyCallback callback) {
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.child("Users").child(uid).child("userName").getValue(User.class);
if (null!=callback) callback.onSuccess(user);
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Log.d(TAG, "onCancelled: Error: " + databaseError.getMessage());
}
});
}
And then I have an interface that deals with the callback
public interface MyCallback{
void onSuccess(User user);
}
And then finally I call the getUser() void where I want the username displayed through this code.
final TextView navuserName = findViewById(R.id.navUsername);
getUser(new MyCallback() {
#Override public void onSuccess(User u) {
navuserName.setText("hello");
}
});
And where navuserName.setText("hello"); is, I want that to display the username. But I do not know what to put between the brackets in order to get the String that the getUser() void is retrieving.
This is how my database is setup
{"BP07KgV4yHa0bqpt740kuFzJQGI2" : {
"email" : "sampleEmail#gmail.com",
"userName" : "testUsername"
In your User class you need getter and setter for your field, in this case, user name.
Add them like this to the String variable that you use to store user name in your User class:
private String username;
public String getusername()
{
return this.username;
}
public void setusername(String value)
{
this.username= value;
}
// If you don't want User class to be initialized without passing a user name then you can add user name to it's constructor
public class User ( String username )
{
this.username = username;
}
To get user from Firebase you should refer to all data in this case uid node. But if you only want to get the user name then you should use it like this:
User user = new User();
String username;
username = (String) dataSnapshot.child("Users").child(uid).child("userName").getValue();
user.setusername(username);
And to retrieve the data in order to pass to the TextView use user.getusername()
I want to retrieve posts posted by currently loggedin user. But with current code all the posts are getting retrieved. How to retrieve expected data by using the uid from customer table?
post_id is primary key of Customer table not customerid(uid).
Get a reference of the current user and use it to query post posted by the user like this:
FirebaseUser user =FirebaseAuth.getInstance().getCurrentUser();
Query reference;
reference = FirebaseDatabase.getInstance().
getReference("customers").orderByChild("customerId").equalTo(user.getUid());
reference.addListenerForSingleValueEvent(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String
customerId =datas.child("customerId").getValue().toString();
String
customerName =datas.child("customerName").getValue().toString();
String
phone =datas.child("phone").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try like this ,
Step 1. Get the right child node , and query on it by getting the current logded user uid:-
String currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("customers").orderByChild("customerId").equalTo(currentLoginId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
List<Customers> customers = new ArrayList<>();
while (dataSnapshots.hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshots.next();
Customers user = dataSnapshotChild.getValue(Customer.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I've just started trying to use Firebase in my Android application. I can write data into the database fine but I'm running into a problem when trying to retrieve data.
My database is structured as below
My method for retrieving the data:
public void getCurrentUserData() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser loggedUser = firebaseAuth.getCurrentUser();
String uid = loggedUser.getUid();
DatabaseReference userRef = database.getReference().child("Users").child(uid);
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//crashes because user is not a string
//User user = dataSnapshot.getValue(User.class);
//works because function is returning first child of uID as a string
String user = dataSnapshot.getValue().toString();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
When debugging:
dataSnapshot = "DataSnapshot { key = bio, value = test }"
I was expecting this to return all children contained within uid (bio, dob, firstName, joinDate, lastName, location) and put them into my User object but it actually looks as if its only returning the first child node (bio) as a string.
Why is this happening and how do I retrieve the full set of child nodes?Any help appreciated. Thanks.
If you want to get all properties of the user, you will either need to create a custom Java class to represent that user, or you will need to read the properties from the individual child snapshots in your own code. For example:
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String firstName = dataSnapshot.child("firstName").getValue(String.class);
String lastName = dataSnapshot.child("lastName").getValue(String.class);
...
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
Alternatively you can loop over the properties with:
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot propertySnapshot: dataSnapshot.getChildren()) {
System.out.println(propertySnapshot.getKey()+": "+propertySnapshot.getValue(String.class));
}
}
I want to retrieve all the doctors' "Firstname" and "Lastname" when I know the "Speciality" of doctor.That's mean when I select specific Specialty area of doctor I want to get all the doctors names which have that Specialty.
To be able to do that try the following:
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference().child("User").child("doctor");
dbRef.orderByChild("Spciality").equalTo("Pathologist").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String firstName=datas.child("Firstname").getValue().toString();
String lastName=datas.child("Lastname").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
the snapshot is at child doctor then to retrieve based on the speciality value you need to use the query orderByChild("Spciality").equalTo("Pathologist") to be able to do that. You can change Pathologist as per your requirement.