Calling too many firebase function in one method - android

I'm currently making a method that allows current logged in user to sign up a new user and add them into as their downline friends using firebase. And while i was developing this method i realise that I've been bloating too much firebase functions into one method and i believe this would cause trouble when something is wrong with the inner function.
private void ValidateAccount(final String name, final String phone,final String email,
final String password, final String confirmPassword,
final String points,
final DatabaseReference RootRef, final FirebaseAuth firebaseAuth) {
firebaseAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
final FirebaseUser userkey = firebaseAuth.getCurrentUser();
final String userkeyString = userkey.getUid();
RootRef.child(userkeyString)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!(dataSnapshot.exists())){
HashMap<String, Object> userDatamap = new HashMap<>();
final HashMap<String, Object> currentUserDatamap = new HashMap<>();
userDatamap.put("id",userkeyString);
userDatamap.put("phone",phone);
userDatamap.put("name",name);
userDatamap.put("email",email);
userDatamap.put("upline", upline);
addNewDownline(userkeyString);
currentUserDatamap.put("downlines", downlinesMaps);
RootRef.child(userkeyString).updateChildren(userDatamap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
RootRef.child(currentUser.getId()).updateChildren(currentUserDatamap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(RegisterDownlineActivity.this, "Congratulations your account has been created.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
firebaseAuth.signOut();
Intent intent = new Intent(RegisterDownlineActivity.this, HomeActivity.class);
startActivity(intent);
}
else{
loadingBar.dismiss();
Toast.makeText(RegisterDownlineActivity.this, "Network Error: Please try again.", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterDownlineActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterDownlineActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
else{
Toast.makeText(RegisterDownlineActivity.this,"The username already belong to someone else.",Toast.LENGTH_LONG).show();
loadingBar.dismiss();
Toast.makeText(RegisterDownlineActivity.this, "Please try again using another username.", Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegisterDownlineActivity.this, MainActivity.class);
startActivity(intent);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(RegisterDownlineActivity.this, "System Error. Please try again later.", Toast.LENGTH_SHORT).show();
}
});
}
else{
Log.d( "FAIL", String.valueOf(task.getException()));
Toast.makeText(RegisterDownlineActivity.this, "Authentication failed."+String.valueOf(task.getResult()),
Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
try{
Toast.makeText(RegisterDownlineActivity.this, "Authentication failed: Email is already being used",
Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
catch (RuntimeExecutionException task){
Toast.makeText(RegisterDownlineActivity.this, "Authentication failed: Email is already being used",
Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
For example, if something is wrong with the updateChildren() then the method will show failure at the updateChildren() part, but the createUserWithEmailAndPassword() will still execute.
What i wish to achieve is that whenever there's an error in the function all the function will not execute and shows the error.

If createUserWithEmailAndPassword() executed and updateChildren() failed, then inside .addOnFailureListener you can delete the user:
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.delete();
Toast.makeText(RegisterDownlineActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});

Related

login different users from different collections on android studio using firebase firestore auth

I have 2 kinds of users for my android app -User and Donor and they are from different collections.
the problem is when I try to use the email and password of a User for the Donor instead of making a Toast saying "cannot log in" the app just crashes. I tried using .addOnFailureListener here but it doesnt work
anyways here's my code.
public class log_in extends AppCompatActivity {
EditText lEmail, lPassword;
Button btnLogIn;
Spinner UserDonor;
FirebaseAuth lFirebaseAuth;
FirebaseFirestore lFirestoreFirebase;
String userID, donorID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activtiy_log_in);
lEmail = findViewById(R.id.etxtEmailLogIn);
lPassword = findViewById(R.id.etxtPasswordLogIn);
UserDonor = findViewById(R.id.spnUserDonor);
lFirebaseAuth = FirebaseAuth.getInstance();
lFirestoreFirebase = FirebaseFirestore.getInstance();
btnLogIn = findViewById(R.id.btnLogIn);
//button log-in
btnLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Email = lEmail.getText().toString().trim();
String Password = lPassword.getText().toString().trim();
String userDonor = UserDonor.getSelectedItem().toString().trim();
//if User is selected on spinner
if (userDonor.equals("User")){
// authenticate the user
lFirebaseAuth.signInWithEmailAndPassword(Email, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
userID = lFirebaseAuth.getCurrentUser().getUid();
DocumentReference userRef = lFirestoreFirebase.collection("users").document(userID);
userRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String usertype;
usertype = documentSnapshot.getString("userType");
if (usertype.equals("user")){
startActivity(new Intent(getApplicationContext(), main_user.class));
finish();
}
else {
Toast.makeText(log_in.this, "no user account is Registered", Toast.LENGTH_SHORT).show();
lFirebaseAuth.signOut();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(log_in.this, "cannot login" + task.getException().getMessage() , Toast.LENGTH_SHORT).show();
lFirebaseAuth.signOut();
}
});
}
else {
Toast.makeText(log_in.this, "cannot login" + task.getException().getMessage() , Toast.LENGTH_SHORT).show();
lFirebaseAuth.signOut();
}
}
});
}
//if Donor is selected on spinner
else if (userDonor.equals("Donor")){
// authenticate the donor
lFirebaseAuth.signInWithEmailAndPassword(Email, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
donorID = lFirebaseAuth.getCurrentUser().getUid();
DocumentReference donorRef = lFirestoreFirebase.collection("donors").document(donorID);
donorRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String usertype;
usertype = documentSnapshot.getString("userType");
if (usertype.equals("donor")){
startActivity(new Intent(getApplicationContext(), main_user.class));
Toast.makeText(log_in.this, "donor Logged in", Toast.LENGTH_SHORT).show();
finish();
}
else {
Toast.makeText(log_in.this, "no donor account is Registered", Toast.LENGTH_SHORT).show();
lFirebaseAuth.signOut();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(log_in.this, "cannot login" + task.getException().getMessage() , Toast.LENGTH_SHORT).show();
lFirebaseAuth.signOut();
}
});
}
else {
Toast.makeText(log_in.this, "cannot log in" + task.getException().getMessage() , Toast.LENGTH_SHORT).show();
lFirebaseAuth.signOut();
}
}
});
}
}
});
}
}
or is there a better way for this to work?

Unable to save data in Firebase Realtime Database from Android app

progress dialog does not dismiss and because of no response from firebase real-time database
I add also authentication another page its works, but save information in realtime won't work, I create a firebase real-time bucket also
this is a simple test but no response progress is running.
btnLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt_email=email.getText().toString();
String txt_password=password.getText().toString();
final ProgressDialog progressDialog =new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Loging in");
progressDialog.show();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("User");
reference.push().setValue("hi").addOnCompleteListener(new OnCompleteListener<Void () {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(LoginActivity.this, "success", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(LoginActivity.this, "no success "+ task.getException().getMessage()
, Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, "fail : "+e.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
});
this is my rules of realtime data base
this is my real time data base
This is actually my firebase integration works or not
and registration code is below. authentication works but real-time not works. don't store data and don't give me any type of message. and progress dialog is running not dismiss because of real-time not response.
private void register(final String username, final String email, String password, final String phone){
auth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
FirebaseUser firebaseUser=auth.getCurrentUser();
assert firebaseUser!=null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
HashMap<String ,String> hashMap= new HashMap<>();
hashMap.put("id", userid);
hashMap.put("username", username);
hashMap.put("imageUrl","default");
hashMap.put("email",email);
hashMap.put("phone",phone);
Toast.makeText(RegisterActivity.this, "sign in but not insert", Toast.LENGTH_SHORT).show();
reference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
/* SharedPreferences preferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(STATUS,"student");
editor.apply();*/
Toast.makeText(RegisterActivity.this, "finish set up", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
Intent intent= new Intent(RegisterActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}else {
Toast.makeText(RegisterActivity.this, "failed to add database", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}else{
Toast.makeText(RegisterActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
please help me how can I fix the real-time database?

Role-based authentification in android app using Firebase

I am developing an android app and using firebase database. It contains authorization and few activities for different roles. If you are entering as "Installer" opens one activity and if as "Contact-Centre" - another, but now it's not important. So I need to check a role of entered pair of email and password. So what I should to do?
Here is my database structure:
Sign in code:
mAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this,"Аутентификация прошла успешно",Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),RoleInstallerForm.class));
}
else {
Toast.makeText(MainActivity.this,"Проверьте правильность введённых данных", Toast.LENGTH_SHORT).show();
ProgressBar.setVisibility(View.GONE);
}
}
});
Modify your code to this:
mAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this,"Àóòåíòèôèêàöèÿ ïðîøëà óñïåøíî",Toast.LENGTH_SHORT).show();
try {
currentUserUID = FirebaseAuth.getInstance().getCurrentUser().getUid();
}catch (Throwable throwable){
throwable.printStackTrace();
}
roleRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserUID).child("Role");
roleRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
String userRole = dataSnapshot.getValue().toString();
//Add if-else here if you need any
//For example:
//I DONT UNDERSTAND RUSSIAN ROLE YOU TYPE
// JUST REPLACE THE ROLE NAMES
if(userRole.equals(leader)){
startActivity(new Intent(MainActivity.this, some-activity.class));
}else{
startActivity(new Intent(MainActivity.this, other-activity.class));
}
}catch (Throwable e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.toString(), Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(MainActivity.this,"Ïðîâåðüòå ïðàâèëüíîñòü ââåä¸ííûõ äàííûõ", Toast.LENGTH_SHORT).show();
ProgressBar.setVisibility(View.GONE);
}
}
});

setValue() not working in firebase realtime database

I'm trying to create new data in the firebase realtime database
I tried to use a HashMap and an object, none of them works.
even when I put the OnComplete/OnSuccess/OnFailure listeners I don't receive any data in the log.
private void registerUser(final String displayName, String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser currentUser = mAuth.getCurrentUser();
String uid = currentUser.getUid();
HashMap<String, String> userMap = new HashMap<>();
User user = new User(displayName, "Bonjour!", "par defaut", "def");
userMap.put("name", displayName);
userMap.put("status", "Bonjour!_Je_viens_de_m'inscirire");
userMap.put("image", "par_defaut");
userMap.put("thumb_image", "def");
Log.d(TAG, "onComplete: " + userMap);
Log.d(TAG, "onComplete: " + user);
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users").child(uid);
mDatabaseReference.setValue(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: ");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
});
Log.d(TAG, "onComplete: " + mDatabaseReference);
mRegProgressBar.setVisibility(View.GONE);
Intent maintIntent = new Intent(RegisterActivity.this, MainActivity.class);
maintIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(maintIntent);
finish();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
mRegProgressBar.setVisibility(View.GONE);
Toast.makeText(RegisterActivity.this, "impossible d'inscrire, veuillez ressayer!", Toast.LENGTH_LONG).show();
}
I tried adding this code and it gives me :" not connected " in the log.
//check if connected
DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
Log.d(TAG, "connected");
} else {
Log.d(TAG, "not connected");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.w(TAG, "Listener was cancelled");
}
});
the HashMap contains the actual data but the setValue() method does not work for some reason. When I look in the firebase console there are no changes.
the code responsible for changing the activity from RegisterActivity to MainActivity ran before actually being able to send the data to the database.
to solve the problem I just put the part of the code responsible for changing the activity and all that:
mRegProgressBar.setVisibility(View.GONE);
Intent maintIntent = new Intent(RegisterActivity.this, MainActivity.class);
maintIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(maintIntent);
finish();
inside the OnSuccessListener.
so the final code is:
private void registerUser(final String displayName, String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser currentUser = mAuth.getCurrentUser();
String uid = currentUser.getUid();
HashMap<String, String> userMap = new HashMap<>();
userMap.put("name", displayName);
userMap.put("status", "Bonjour!_Je_viens_de_m'inscirire");
userMap.put("image", "par_defaut");
userMap.put("thumb_image", "def");
mDatabaseReference = mDatabase.getReference("Users").child(uid);
mDatabaseReference.setValue(userMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: ");
mRegProgressBar.setVisibility(View.GONE);
Intent maintIntent = new Intent(RegisterActivity.this, MainActivity.class);
maintIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(maintIntent);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
});
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
mRegProgressBar.setVisibility(View.GONE);
Toast.makeText(RegisterActivity.this, "impossible d'inscrire, veuillez ressayer!", Toast.LENGTH_LONG).show();
}
}
});
thanks for the commenters.

Android (Firestore): Unable to add or update or set (SetOptions.merge) fields in already created document in Firestore

I am trying to add new fields to an already created document under "users" collection in firestore database.
From first activity I added basic information like name and description and gender to the firestore database (collection("users").document(uid)) and it worked. But when I am trying to add new fields (from second activity) to the same document it is not working. I tried to use set, SetOptions.merge, update, but nothing is working. Even I tried to add new collection then also it is not working. Can someone please help me to figure this out. Thanks in advance.
My codes are below from both the activities.
First Activity (BasicInfo.java) (working)
String uid = user.getUid();
Map<String, Object> dataToSave = new HashMap<>();
dataToSave.put(NAME, nameText);
dataToSave.put(ABOUT, aboutText);
dataToSave.put(GENDER, userGender);
db.collection("users").document(uid).set(dataToSave).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent userPreIntent = new Intent(BasicInfo.this, UserPre.class);
startActivity(userPreIntent);
finish();
} else {
Toast.makeText(getApplicationContext(), "There was some problem", Toast.LENGTH_SHORT).show();
}
}
});
Second Activity (UserPre.java) (Not working)
Map<String, Object> data = new HashMap<>();
data.put(STYLE, styleBeauty);
data.put(HUMOR, humor);
data.put(FITNESS, fitness);
data.put(TRAVEL, travel);
data.put(PHOTOGRAPHY, photography);
data.put(MUSIC, music);
data.put(DANCE, dance);
data.put(ART, art);
data.put(FASHION, fashion);
String uid = user.getUid();
db.collection("user").document(uid).set(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Data Added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "There was some problem", Toast.LENGTH_SHORT).show();
}
}
});
You can add a FailureListener and it will tell you what's wrong in logcat.
db.collection("user").document(uid).set(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Data Added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "There was some problem", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});

Categories

Resources