mixed up data in firebase database data - java

I am new to firebase and Android programming in general. In my app I'm simply saving fullName, password, phoneNumber, Email, gender and a confirmed password. All these fields get stored in the database but their mixed up
Users
+23407066082195
email: '0000'
fullName: '+23407066082195'
gender: 'male'
password: 'k..gmail.com'
phoneNo: 'Tim...'
retypedPassword: '0000'
this is my code : for the first activity
btnSignUp = findViewById(R.id.btnSignUp);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!validateEdtName() | !validateEdtEmail() | !validatePhoneNumber() | !validateEdtPassword() | !validateEdtRePassword() | !validateGender()) {
return;
}
progressBar.setVisibility(View.VISIBLE);
selectedGender = findViewById(gender.getCheckedRadioButtonId());
String gender = selectedGender.getText().toString();
String myName = fullName.getEditableText().toString().trim();
String myEmail = email.getEditableText().toString().trim();
String myPassword = password.getEditableText().toString().trim();
String myRetypedPassword = retypedPassword.getEditableText().toString().trim();
String getUserEnteredPhoneNumber = phoneNumber.getEditableText().toString().trim();
String phoneNo = "+" + countryCodePicker.getFullNumber() + getUserEnteredPhoneNumber;
Intent intent = new Intent(SignUp.this, VerifyOTP.class);
intent.putExtra("PhoneNumber", phoneNo);
//intent.putExtra("fullName", fullName);
intent.putExtra("myName", myName);
intent.putExtra("myEmail", myEmail);
intent.putExtra("myPassword", myPassword);
intent.putExtra("myRetypedPassword", myRetypedPassword);
intent.putExtra("gender", gender);
startActivity(intent);
for the next activity: created a class to hold the strings which is the UserHelperClass
FirebaseDatabase rootNode = FirebaseDatabase.getInstance();
DatabaseReference reference = rootNode.getReference("Users");
UserHelperClass addNewUser = new UserHelperClass(fullName,phoneNo,password,email,retypedPassword,gender);
reference.child(phoneNo).setValue(addNewUser);
any suggestions will be helpful.

I analyzed your code. Either you haven't correctly initialized your EditTexts (maybe their ids aren't correct) or you haven't correctly implemented the constructor of UserHelperClass. Check both of them, you will probably see the bug.
P.S. I would encourage you to check Parcelable documentation. It is for sharing objects via intents.

Related

How to make the new added item sit under the existed id in firebase?

I have problem where the new added item created a new id instead of sit under the existed id
database
The picture above show that the yellow highlighted id is the existed id. The red on is the new added item. I have problem where the added item created a new id instead of sitting on the existed id in the highlighted id.
Result that I want to achieve is. I wanted the new added item sit under the highlighted id instead of creating the new id.
databaseReference = FirebaseDatabase.getInstance().getReference("Cart");
private void addCart() {
final String id = databaseReference.push().getKey();
Intent intent = getIntent();
final String cust_id = firebaseAuth.getCurrentUser().getUid();
final String pid = intent.getStringExtra("pid");
String keyB = intent.getStringExtra("keyB");
String name = pname.getText().toString().trim();
String category = pcategory.getText().toString().trim();
String price = pprice.getText().toString().trim();
String size = psize.getSelectedItem().toString().trim();
String quantity = pquantity.getText().toString().trim();
String image = intent.getStringExtra("pro_image");
final Cart cart = new Cart(id, pid, cust_id, keyB, name, price, image, category, quantity, size);
databaseReference.child("Cust List").child(cust_id).child(id).child(pid).setValue(cart) //table and primary key
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
databaseReference.child("PS List").child(cust_id).child(id).child(pid).setValue(cart).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "add Successfully", Toast.LENGTH_SHORT).show();
AddToCart.super.onBackPressed();
}
}
});
}
}
}
);
}
Every time,after cust_id when you added data in your database, a new id is generated. Thats's mean databaseReference from cust_id is always same, after cust_id it changed. So, you need to keep databaseReference unchanged from here,
databaseReference.child("Cust List").child(cust_id).child(id)
When you use .push keyword, it always generated a new id. But you need to keep it always same like cust_id.So, if you use same reference from ----.child(id), when you add data in database, i think the problem will solve.

Firebase Cloud Firestore referrence returning 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);

Firebase realtime database doesn't update database when i sign up

I am trying to send information to the firebase database, I am connected and already checked multiple times and i can't find the error here's my code
Here's the database reference command
everything is well put together and working, i don't exactly know why it doesn't really allow me to send information doesn't show any errors and everything
userInformation = FirebaseDatabase.getInstance().getReference("Users").child("Users");
firebaseAuth = FirebaseAuth.getInstance();
private void saveUserInformation(){
String UserName = NameET.getText().toString();
String Userbirthday = dateBirth.toString();
String Userdate_drivinglicense = dateLicense.toString();
String UserCountry = Countries.getSelectedItem().toString();
String UserGender = Genders.getSelectedItem().toString();
String HouseLocationLat = String.valueOf(location.getLatitude());
String HouseLocationLong = String.valueOf(location.getLongitude());
Userinformation userInfo = new Userinformation(UserName,Userbirthday,Userdate_drivinglicense,UserCountry,UserGender,HouseLocationLat,HouseLocationLong);
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
userInformation.child(user.getUid()).setValue(userInfo);
}
Toast.makeText(UserInformationActivity.this, "Saving Information", Toast.LENGTH_SHORT).show();
}
The Issue i had was that i didn't implent an Getter and Setter in my Java Class which is connected to the UserInformation, and i had to create a new child in the database with the name "Users" since it wasn't created automatically as it should be, also changed the names of variables in my
Userinformation userInfo = new Userinformation(UserName,Userbirthday,Userdate_drivinglicense,UserCountry,UserGender,HouseLocationLat,HouseLocationLong);
So it can connect to the database correctly Thanks for all the help :)

Firebase realtime database not registering data Android

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);

access the .push key of firebase database for updating Profile info in android

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.

Categories