Here is the code, in which I retrieve data from Firestore.
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private DocumentReference dataRef = db.collection("users").document(currentUser);
dataRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()){
navUserName.setText(documentSnapshot.getString("fullname"));
navGmail.setText(documentSnapshot.getString("email"));
} else {
Log.i("current user data: ","Not Found");
}
}
});
I want to assign this data first to class user object and then want to retrieve it from class user object. How can I do this?
According to your comment, if you are adding the data to the database using a User object, to get the data back, you can map the DocumentSnapshot object to a User object using the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DocumentReference dataRef = db.collection("users").document(uid);
dataRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
User user = documentSnapshot.toObject(User.class);
Log.d(TAG, user.getFullname());
}
});
Related
Please tell me what is my mistake? I'm trying to count the pricecode and shove it into user -> price. But instead, it gives an error or a link, and not the value "1000"
enter image description here
public void onClickB1 (View view)
{
DatabaseReference bd = FirebaseDatabase.getInstance().getReference("User");
DatabaseReference bd1 = bd.child("pricecode");
String id = mDataBase.getKey();
//String key = dataSnapshot.getKey();
String name = String.valueOf(textB1.getText());
**String price = bd1.child("pricecode").getValue(String.class);**
User newUser = new User(id,name,price);
//mDataBase.push().setValue(newUser);
if (!TextUtils.isEmpty(name)) // проверка пустой строки
{
mDataBase.push().setValue(newUser);
}
else
{
Toast.makeText(this,"Заполните поля",Toast.LENGTH_LONG).show();
}
}
There is no way you can call getValue() on an object of the type DatabaseReference. Why? Because there is no such method inside the class. On the other hand, DataSnapshot class contains a getValue() method. So to be able to read that value, you have to attach a listener as in the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = db.child("User");
userRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
String priceCode = snapshot.child("pricecode").getValue(String.class);
Log.d("TAG", "priceCode: " + priceCode);
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
As I already mentioned in an earlier question of yours, store the prices as numbers and not strings.
What is the proper way to read data from Firebase Realtime Database? I have created a database "Mybill"s with child bills. In child Bills, I am saving UserId from FirebaseAuth so it should be easy to find bills for a specific user and in userID child, I have a child that I have created using the .push() method and in that, I have data about the bill.
It looks like this:
How should I change my Java code so I can get all the bills saved for a specific user (the user that is currently logged in)
this is my code for now :
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("bills");
Query checkUser = ref.orderByChild("UserId").equalTo(Autentication.GetUser());
// Attach a listener to read the data at our posts reference
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.child("email").getValue(String.class);
String market = dataSnapshot.child("market").getValue(String.class);
String price = dataSnapshot.child("price").getValue(String.class);
String date = dataSnapshot.child("date").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
How should I change my Java code so I can get all the bills saved for a specific user (the user that is currently logged in)
To do that, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("bills").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String email = ds .child("email").getValue(String.class);
String market = ds .child("market").getValue(String.class);
String price = ds .child("price").getValue(String.class);
Log.d("TAG", email + "/" + market + "/" + price);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The "date" cannot be read as a String, as it's an object. So the most appropriate way would be to read it as a Map<String, Object>. In this way, you are getting only the bills that correspond to a specific user (logged-in user).
Data is stored only in list/0.
I want multiple data to be stored in the user's email.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
FirebaseFirestore db = FirebaseFirestore.getInstance();
final ArrayList<AddDayInfo> list = new ArrayList<>();
final Map<String,Object> docData = new HashMap<>();
AddDayInfo memberInfo = new AddDayInfo(Type,Day,Name,Time1,Time2,Time3);
list.add(memberInfo);
for(int i=0;i<list.size();i++) {
if (user != null) {
docData.put("Day_M", list);
db.collection("day").document(user.getEmail()).set(docData, SetOptions.merge())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
startToast("Okay. Add Data..");
myStartActivity(Add_Main_Activity.class);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
startToast("Failed...");
}
});
}
}
I want to add data like this picture:
To add an item to an array in Firestore, you have two options:
Use FieldValue.arrayUnion which ensures you have only unique elements in the array.
Read the entire array, change it in your application code, and write it back.
The choice between these two depends on the meaning of your data, and I expect you'll actually need the second (more involved) option here.
We'll start with FieldValue.arrayUnion, just to show you how to do it:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference docRef = db.collection("day").document(user.getEmail())
AddDayInfo memberInfo = new AddDayInfo(Type,Day,Name,Time1,Time2,Time3);
docRef.update("messages", FieldValue.arrayUnion(memberInfo))...
If you always want to add the message to the end of the array, even if another copy of the message is already in there, you'll need to:
Read the current contents of the array
Change the array in your application code
Write the full array back to the database
Since we're using the current value to determine the new value, it's best to use a transaction for this:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference docRef = db.collection("day").document(user.getEmail())
AddDayInfo memberInfo = new AddDayInfo(Type,Day,Name,Time1,Time2,Time3);
db.runTransaction(new Transaction.Function<Void>() {
#Override
public Void apply(Transaction transaction) throws FirebaseFirestoreException {
DocumentSnapshot snapshot = transaction.get(docRef);
List messages = snapshot.get("messages");
messages.add(memberInfo)
transaction.update(docRef, "messages", messages);
// Success
return null;
}
})
So, I create firebase user profile in firestore, it will save users data such as their name, email, phone number, and their reward point. The user logged in using Google Sign-in.
This is how I write the data to firestore.
private void addNewUser() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
String uid = user.getUid();
for (UserInfo profile : user.getProviderData()) {
// Id of the provider (ex: google.com)
String providerId = profile.getProviderId();
// UID specific to the provider
// Name, email address, and profile photo Url
String name = profile.getDisplayName();
String email = profile.getEmail();
Map<String, Object> newUser = new HashMap<>();
newUser.put("Nama", name);
newUser.put("Email", email);
// Add a new document with a generated ID
db.collection("users").document(uid).set(newUser);
}
}
}
And that one works.
But when I try to retrieve the data using Document Reference
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
String curUser = user.getUid();
DocumentReference documentReference = db.document(curUser);
documentReference.addSnapshotListener(this.getActivity(), new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable DocumentSnapshot documentSnapshot, #javax.annotation.Nullable FirebaseFirestoreException e) {
if (documentSnapshot.exists()) {
String userNama = documentSnapshot.getString(KEY_NAMA);
String userEmail = documentSnapshot.getString(KEY_EMAIL);
namaUser.setText(userNama);
emailUser.setText(userEmail);
}
}
});
} else {
Intent intent = new Intent(Home.this.getActivity(), LoginActivity.class);
startActivity(intent);
}
}
The document reference curUser in this case, returning null. I didn't know what did I do wrong.
You need to have the collection name (users) in your DocumentReference
Change,
DocumentReference documentReference = db.document(curUser);
to,
DocumentReference documentReference = db.collection("users").document(curUser);
so i am stuck. i want to retrieve child of child from my firebase database.
my database struture looks like this
users{
user1{
name:
regno:
carmodel:
caryear}
user2{
name:
regno:
carmodel:
caryear}
user3{
name:
regno:
carmodel:
caryear}}
Regno = car registration number.
when i type in a "carreg no" and press ok. i want the code to search every carreg. if a match is found execute next set of codes.
so far i have tried to store it in a array. but the code seems to fail when i put reg or any variable name that exist.
public void input(){
FirebaseDatabase firebase = FirebaseDatabase.getInstance();
final DatabaseReference table_user = firebase.getReference("User");
table_user.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get map of users in datasnapshot
collectPhoneNumbers((Map<String,Object>) dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
//handle databaseError
}
});
private void collectPhoneNumbers(Map<String,Object> users) {
ArrayList<Long> phoneNumbers = new ArrayList<>();
//iterate through each user, ignoring their UID
for (Map.Entry<String, Object> entry : users.entrySet()){
//Get user map
Map singleUser = (Map) entry.getValue();
//Get phone field and append to list
phoneNumbers.add((Long) singleUser.get("namesd"));
}
System.out.println(phoneNumbers.toString());
mVoiceInputTv.setText("" + phoneNumbers);
}
}
i got this from another stackflow. before this i tried creating a for look. it was successfull but result failed 80% of the time. (not always correct).
To solve this, you need to query your database using orderByChild() method like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
Query regnoQuery = usersRef.orderByChild("regno").equalsTo(regno);
In which regno argument from equalsTo() is the the actual registration number that you are looking for. Then attach a listener to the regnoQuery and use getChildrenCount() method on the dataSnapshot object. If the number of childrens is noOfChildrens > 0 then execute the set of codes you need.
private FirebaseDatabase mdatabase;
private DatabaseReference mdatabaseRef;
mdatabase = FirebaseDatabase.getInstance();
mdatabaseRef = mdatabase.getReference();
mdatabaseRef.child("users").child("users1").orderByChild("regno").equalsTo(regno).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
}
}