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);
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.
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;
}
})
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());
}
});
I'm trying to add a table "user" to my Firebase real-time database, code wise everything looks fine but there are no registers showing!
Here's my code sample:
private void CreateUser(){
final TextView firstName = findViewById(R.id.signUpOnSuccess_FirstName), lastName = findViewById(R.id.signUpOnSuccess_LastName);
final EditText bday = findViewById(R.id.SignUpOnSuccess_Bday);
final Spinner gender = findViewById(R.id.signUpOnSuccess_Gender);
final String sFirstName = firstName.getText().toString().trim(),
sLastName = lastName.getText().toString().trim(),
sGender = gender.getSelectedItem().toString();
//Transfer from SignUpActivity.java
String sEmail = SignUpActivity.sEmail,
sPassword = SignUpActivity.sPassword;
if (!TextUtils.isEmpty(sFirstName)) {
if (!TextUtils.isEmpty(sLastName)) {
String id = databaseUsers.push().getKey();
User user = new User(id, sEmail, sPassword, sFirstName, sLastName, sGender);
databaseUsers.child(id).setValue(user);
Toast.makeText(getApplicationContext(), "User Entry Successfull", Toast.LENGTH_SHORT).show();
}else {Toast.makeText(getApplicationContext(), "Enter Last Name!", Toast.LENGTH_SHORT).show();}
} else {Toast.makeText(getApplicationContext(), "Enter First Name Address!", Toast.LENGTH_SHORT).show();}
}
--"--
String id = databaseUsers.push().getKey();
User user = new User(id, sEmail, sPassword, sFirstName, sLastName, sGender);
databaseUsers.child(id).setValue(user);
Here are my Firebase rules:
Here's what's shown on Firebase Database:
Add this at the beginning of the class:
public FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
public DatabaseReference databaseUsers = databaseUsers.getReference("NameofYourTable");
The rest of your code seems fine:
String id = databaseUsers.push().getKey();
User user = new User(id, sEmail, sPassword, sFirstName, sLastName, sGender);
databaseUsers.child(id).setValue(user);
To try to find out if there is a problem with the operation, you can add the CompletionListener, when you add the data into firebase database.
Change this:
databaseUsers.child(id).setValue(user);
For this:
databaseUsers.child(id).setValue(userAux, new DatabaseReference.CompletionListener() {
public void onComplete(DatabaseError error, DatabaseReference ref) {
if(error == null){
callback.OnSuccess("Ok");
}
else{
callback.OnFailure(error.toString());
}
}
});
Is just checking if the operation is going through(OnSuccess) or if is not (OnFailure), and why not:
error.toString()
Try Giving it some node and save it inside it like :
DatabaseReference databaseUsers = getDatabase().getReference("users");
String id = databaseUsers.push().getKey();
User user = new User(id, sEmail, sPassword, sFirstName, sLastName, sGender);
databaseUsers.child(id).setValue(user);
I am developing an android app with Firebase, so saving data to Firebase with .push method and displaying them into list , i want to update the UserInfo stored in database but confused how i can access push method generated Key to update profile info , or any other way to setting profile info under the Authenticated user ID and read all this data so it will update on the list i am displaying.
or any other method to access this by User_id in child values?
myOnBtnClick code below
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Validation()) {
final String name = Field_fullName.getText().toString();
String phone = firebaseUser.getPhoneNumber();
String bg = field_bloodGroups.getSelectedItem().toString();
String DOB = Field_dateOfBirth.getText().toString();
String state = Field_state.getText().toString();
final String country = Field_country.getText().toString();
String city = Field_city.getText().toString();
UserSignUp userSignUp = new UserSignUp(name, phone, bg, DOB, state, country, city, firebaseUser.getUid());
DBref.child("DONORS").child(country).push().setValue(userSignUp).addOnCompleteListener(reg.this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(reg.this, DBref.getKey() + "", Toast.LENGTH_SHORT).show();
Toast.makeText(reg.this, "User Created", Toast.LENGTH_SHORT).show();
editor = sharedPreference.edit();
editor.putInt("UserReg", 1);
editor.putString("UserCountry", country);
editor.putInt("FirstTimeRun", 1);
editor.apply();
startActivity(new Intent(reg.this, Main2Activity.class));
finish();
}
}
});
}
}
});
When you are using the push() method to generate that unique key, is the moment in which you can get and store the key like this:
String key = yourRef.getKey();
And to update a record please use the following line of code:
FirebaseDatabase.getInstance().getReference()
.child("Pakistan")
.child(key)
.child("user_ID")
.setValue("123456789");
Edit:
DatabaseReference keyRef = DBref.child("DONORS").child(country).push();
String key = keyRef.getKey();
Log("TAG", key);
keyRef.setValue(userSignUp).addOnCompleteListener(/* ... */);
Once you have this key, you can use it in other DatabaseReference. When you are using DBref.getKey() inside onComplete() method isn't getting the pushed key is just getting the key of your DBref.