Unable to save data in Firebase Realtime Database from Android app - android

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?

Related

E Failed to getEnergyData

I wanna register a user in firebase firestore but when I click the register button nothing happens. I don't understand where I went wrong . It doesn't even create the user or send the data to the database
fStore = FirebaseFirestore.getInstance();
signi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mail = regemail.getText().toString().trim();
String pin = pass.getText().toString().trim();
String confarm = confir.getText().toString().trim();
String phon = tele.getText().toString().trim();
fAuth.createUserWithEmailAndPassword(mail, pin).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(registrations.this, "Registration Successful", Toast.LENGTH_SHORT).show();
Map<String, Object> user = new HashMap<>();
user.put("Email", mail);
user.put("Password", pin);
user.put("Phone", phon);
df.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
startActivity(new Intent(registrations.this, login.class));
}
else {
Toast.makeText(registrations.this, "Registration Failed!" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();```
It was working before. I was able to create user and sign in but moving that data to the database is the problem. Also I had used realtime database before and it worked but it was overwtiting the data in the database when I tried to register a new user so I decided to use firestore instead

Calling too many firebase function in one method

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

Verify if a User is new or already exists Android Studio [duplicate]

This question already has an answer here:
Users info are re-initialized after logging out and signing in
(1 answer)
Closed 4 years ago.
i am working on a application and i use firebase for user login authentication and everything works perfect. Recently i thought of a new idea for the app and i would like to check if a user exists or if its the first time. if its the first time the user goes to a new activity and if the user exists it goes to the home activity. i tried documentations and i didn't really understand. Can someone help me with code sample or better explanation.
this is the login code
private void user_login(String email, String password) {
if (email.isEmpty()){
emailtx.setError("email is empty");
emailtx.requestFocus();
}
if (password.isEmpty()){
passwordtx.setError("password is empty");
passwordtx.requestFocus();
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
emailtx.setError("Please enter a valid email");
emailtx.requestFocus();
return;
}
if (password.length()< 6){
passwordtx.setError("password is short");
passwordtx.requestFocus();
}
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser current_user = FirebaseAuth.getInstance().getCurrentUser();
String user_id = current_user.getUid();
String device_token = FirebaseInstanceId.getInstance().getToken();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
HashMap<String, String> userMap = new HashMap<>();
userMap.put("image", "https://firebasestorage.googleapis.com/v0/b/bookshare-8e018.appspot.com/o/male.png?alt=media&token=60cbb24c-b9f9-4724-b8bf-69a76386fcca");
userMap.put("thumb_image", "default");
userMap.put("device_token", device_token);
userMap.put("home", "earth");
userMap.put("work", "earth");
userMap.put("others", "earth");
mDatabase.setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent mainIntent = new Intent(login.this, selectestado.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
});
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(login.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
below mDatabase you can check if the user exists
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
HashMap<String, String> userMap = new HashMap<>();
userMap.put("image", "https://firebasestorage.googleapis.com/v0/b/bookshare-8e018.appspot.com/o/male.png?alt=media&token=60cbb24c-b9f9-4724-b8bf-69a76386fcca");
userMap.put("thumb_image", "default");
userMap.put("device_token", device_token);
userMap.put("home", "earth");
userMap.put("work", "earth");
userMap.put("others", "earth");
mDatabase.setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent mainIntent = new Intent(login.this, selectestado.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
});
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(login.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
}else{
//User does not exists
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});

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

Firebase Android data is being saved incorrectly

The way data is being saved in Firebase is that the User ID is under each Push ID, whereas it should have been the other way around; that is Push ID under User ID.
What do I have to change in my code?
private void saveServiceDetails(){
adService1 adService1 = new adService1(Name, Description, Category, downloadUrl, lat, lng);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Saving information..., please wait");
progressDialog.show();
FirebaseUser user = firebaseAuth.getCurrentUser();
databaseReference.child(user.getUid()).setValue(adService1)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Information saved...", Toast.LENGTH_LONG).show();
}
}
});
}
Try this code :
....
FirebaseUser user = firebaseAuth.getCurrentUser();
String key = databaseReference.child(user.getUid()).push().getKey();
databaseReference.child(user.getUid()).child(key).setValue(adService1)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Information saved...", Toast.LENGTH_LONG).show();
}
}
});

Categories

Resources