I am using Firebase database for my project. For the last few days I tried to retrieve data from database but without luck. I tried many tutorials and questions from Stack.. Database looks like this:
Database structure
My user class
I would like to retrieve information and store it in one of the strings..
My code is:
Every time I receive value Null or an Error. I am not sure If I am using correct reference("Users").
Is there is easy way to retrieve users name and store it into the string? Thanks
First you need to have same names for the fields in your database as in your model class. Looking at you model class, there are some things that you need to do. So, I'll provide a correct way to model your class.
public class UserModelClass {
private String name, sureName, date, phoneNumber;
public UserModelClass() {}
public UserModelClass(String name, String sureName, String date, String phoneNumber) {
this.name = name;
this.sureName = sureName;
this.date = date;
this.phoneNumber = phoneNumber;
}
public String getName() {return name;}
public String getSureName() {return sureName;}
public String getDate() {return date;}
public String getPhoneNumber() {return phoneNumber;}
}
In order to make it work, you need to remove all data from the database and add fresh one. There is a workaround when storing users in a Firebase database. Instead of using that that random key provided by the push() method, to use the uid. For that, I recommend you add the data as in the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
UserModelClass umc = new UserModelClass("Jonas", "Simonaitis", "today", "123456789");
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("users").child(uid);
uidRef.setValue(umc);
To read data, please use the following code:
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserModelClass userModelClass = dataSnapshot.getValue(dataSnapshot.class);
String name = userModelClass.getName();
String sureName = userModelClass.getSureName();
String date = userModelClass.getDate();
String phoneNumber = userModelClass.getPhoneNumber();
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
In one of my tutorials I have explained step by step how to use the model classes when using Firebase.
First you have to do make these declarations:
private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
in onCreate you need to make smth like this:
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = mCurrentUser.getUid();
mUserDatabase =FirebaseDatabase.getInstance().getReference().child("Users")
.child(current_uid);
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("uName").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Now you have the user name in "name"
First change userInformationActivity class variable names to match names in the database
example : name -> uName
surname -> uSurname
then
private void showData(DataSnapshot dataSnapshot){
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
userInformationActivity user = dataSnapshot.getValue(userInformationActivity.class);
Log.d("user Name is : " + user.uName);
}
}
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 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) {
}
});
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) {
}
});
So this is my bind model class:
public class UserBanknoteAmountBindModel {
public String id;
public String userId;
public String banknoteType;
public String banknoteAmount;
public UserBanknoteAmountBindModel(){
}
public String getBanknoteAmount() {
return banknoteAmount;
}
public String getBanknoteType() {
return banknoteType;
}
public String getUserId() {
return userId;
}
public void setBanknoteAmount(String banknoteAmount) {
this.banknoteAmount = banknoteAmount;
}
public void setBanknoteType(String banknoteType) {
this.banknoteType = banknoteType;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
(idk if acess modifiers matter in this case).
I am trying to parse my data:
for (DataSnapshot banknoteAmount:dataSnapshot.getChildren()){
UserBanknoteAmountBindModel userBanknoteAmountBindModel=dataSnapshot.getValue(UserBanknoteAmountBindModel.class);
Log.wtf("hgfh", banknoteAmount.getValue().toString());
}
I see that I am receiving my data because I can log it.
{banknoteAmount=3, banknoteType=20_dollar,
userId=112371098270685247195}
Anyway my data doesn't get inside my bind model. I read somewhere that I need not only to provide getters but also setters (that's why I put those setters PS: Is the thing for the setters true?).
Any ideas?
EDIT: Database Structure https://i.stack.imgur.com/o5Hgp.png
PS: The problem was that I was using the parameter from another function for the getValue (not the foorloop variable)
To get the values of banknoteAmount, banknoteType and userId, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userBanknoteAmountRef = rootRef.child("userBanknoteAmount");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
UserBanknoteAmountBindModel userBanknoteAmountBindModel = ds.getValue(UserBanknoteAmountBindModel.class);
String banknoteAmount = userBanknoteAmountBindModel.getBanknoteAmount();
String banknoteType = userBanknoteAmountBindModel.getBanknoteType();
String userId = userBanknoteAmountBindModel.getUserId();
Log.d("TAG", banknoteAmount + " / " + banknoteType + " / " + userId);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userBanknoteAmountRef.addListenerForSingleValueEvent(valueEventListener);
The output will be:
3 / 20_dollar / 112371098270685247195
When you are using the following line of code:
banknoteAmount.getValue().toString()
You are actually printing the String representation of banknoteAmount.getValue() which has as a return value a Map object which contains those three values.
I am looking for ways to do following:
Whenever a user registers or logs on for first time, then a record should be created in DB with the user's email-id.
Can someone please give directions, I have tried few options from my side, but none worked out correctly.
To Register User And Add Information to database
FirebaseAuth auth = FirebaseAuth.getInstance();
DataBaseRefrence ref = FirebaseData.getInstance().getReference();
auth.createUserWithEmailAndPassword(email,pass)addOnCompleteListener(context, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
FirebaseUser fUser = mAuth.getCurrentUser();
User user = new User(name,email);
ref.child("Users").child(fuser.getUid).setValue(user);
}
User class
public class User
{
public String Name;
public String Email;
// need empty constractor
public User()
{}
public User(String name,String email)
{
Name = name;
email = email;
}
public String getName()
{
return Name;
}
public String getEmail()
{
return Email;
}
To Get Value
DataBaseRefrence ref = FirebaseData.getInstance().getReference();
FirebaseUser fUser = auth.getCurrentUser();
ref.child("Users").child(fUser.getUid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if(user!=null)
{
// do what ever you want
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To Get data from firebase you have to go from child to child
for example to get userdata myRefLinkis https://stackoverflow.com
https://stackoverflow.com/Users/UserId now get the data
so do this,
from your question i conclude that you do not have a separate form for adding new users.
in such case ,
when the user clicks on the logon button,
u can check from the database if the record exists.
for eg. query a simple sql statement
select * from users where email-id="entered value"
if it exists then open the main application
else if it doesn't exists then insert a row with the entered values and then open the application.