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) {
}
});
Related
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) {
}
});
If my tree looks like that:
{
unique_id_1: {
message: "hello"
}
unique_id_2: {
message: "hi there"
}
}
How do I get all messages that are children of each unique id if I don't know the user's unique id? Or I have to build my database so that a message can only be a direct child of a unique id and then traverse like so:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference reference = database.child("message");
Or that would not work?
To get all the messages, you need to loop:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String messages = datas.child("message").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here the datasnapshot is at the root node then if you have unique ids and don't have there values, you can just loop inside these unique ids dataSnapshot.getChildren() and get the messages.
You can also retrieve the unique ids by doing String key = datas.getKey();
I have a database of users with their emails, role and list of contacts.
I have code to add contacts that when you input into the EditText, it checks through the database if the email exists and if it does, it appends the email into the contacts list. However, nothing gets added in my database.
public void searchContacts(final String emailInput){
final DatabaseReference users;
users = FirebaseDatabase.getInstance().getReference("users");
users.orderByChild("email").equalTo(emailInput).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()){
if((userSnapshot.child("email").getValue(String.class).equals(emailInput))){
users.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("contacts").child(emailInput).setValue(true);
}
}
}
Nothing is added, because you haven't create a list yet. To solve this, please use the following code:
public void searchContacts(final String emailInput){
DatabaseReference users = FirebaseDatabase.getInstance().getReference("users");
users.orderByChild("email").equalTo(emailInput).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>(); //Create the list
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()){
String email = userSnapshot.child("email").getValue(String.class);
if(email.equals(emailInput)){
users.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("contacts").child(emailInput).setValue(true);
list.add(email); //Add the email the list
}
}
//Do what you need to do with list
}
}
}
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));
}
}
This is firebase database details
Here I want to search details using child without use parent key. According to this database, I want to get price and category using Name without using parent key ("kjhsfkgkrlhg"), ("get price, category where Name="super Creamcracker")
To solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference itemsRef = rootRef.child("Items");
Query query = itemsRef.orderByChild("Name").equalsTo("super Creamcracker");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String category = ds.child("Category").getValue(String.class);
long price = ds.child("Price").getValue(Long.class);
Log.d("TAG", category + " / " + price);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);
So the ds contains a list of results. Even if there is only a single result, the ds will contain a list of one result. So the output will be:
200g / 200
First, you make database reference first
DatabaseReference itemRef = FirebaseDatabase.getInstance().getReference("Items");
then,
String itemName = "super Creamcracker";
Query query = itemRef.orderByChild("Name").startAt(itemName).endAt(itemName+ "\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
//if you dont have class for item
String price = data.child("Price").getValue().toString();
String category = data.child("Category").getValue().toString();
//if you have class, lets say Item.java
Item item = data.getValue(Item.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});