E Failed to getEnergyData - android

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

Related

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?

failed to create account with firebase?

i tried to do everything correctly and can't seem to find what's wrong here, i even created the project again from scratch but still it doesn't work, but i get the "failed" toast when trying to create an account, i added the internet permission too. i also don't get any error in logcat to show it here, how can this be solved ?
public class CreateAccountActivity extends AppCompatActivity {
private Button btnCreateAcc;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser currentUser;
// firestore
private FirebaseFirestore database = FirebaseFirestore.getInstance();
private CollectionReference collectionReference = database.collection("Users");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
firebaseAuth = FirebaseAuth.getInstance();
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
currentUser = firebaseAuth.getCurrentUser();
if (currentUser != null) {
} else {
}
}
};
btnCreateAcc = findViewById(R.id.create_acct_button);
btnCreateAcc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(etEmail.getText().toString()) &&
!TextUtils.isEmpty(etPassword.getText().toString()) &&
!TextUtils.isEmpty(etUserName.getText().toString())) {
String email = etEmail.getText().toString();
String password = etPassword.getText().toString();
String username = etUserName.getText().toString();
createUserEmailAccount(email, password, username);
} else {
Toast.makeText(CreateAccountActivity.this, "Please fill in all fields"
, Toast.LENGTH_SHORT).show();
}
}
});
}
private void createUserEmailAccount(String email, String password, final String username) {
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password) &&
!TextUtils.isEmpty(username)) {
progressBar.setVisibility(View.VISIBLE);
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
currentUser = firebaseAuth.getCurrentUser();
assert currentUser != null;
final String currentUserId = currentUser.getUid();
Map<String, String> userObj = new HashMap<>();
userObj.put("userId", currentUserId);
userObj.put("username", username);
collectionReference.add(userObj)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
documentReference.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (Objects.requireNonNull(task.getResult()).exists()) {
progressBar.setVisibility(View.INVISIBLE);
String name = task.getResult()
.getString("username");
Intent intent = new Intent(CreateAccountActivity.this,
PostJournalActivity.class);
intent.putExtra("username", name);
intent.putExtra("userId", currentUserId);
startActivity(intent);
} else {
progressBar.setVisibility(View.INVISIBLE);
}
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(CreateAccountActivity.this, "failed"
, Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(CreateAccountActivity.this, "failed task"
, Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(CreateAccountActivity.this, "failed on complete"
, Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "failed else", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onStart() {
super.onStart();
currentUser = firebaseAuth.getCurrentUser();
firebaseAuth.addAuthStateListener(authStateListener);
}
}
i fixed, the problem was i had allow read, write: if false; in firestore
and it needed to be allow read, write: if true;
This could be solved by following good debugging practices.
Meaningful error messages
When you encounter an error and wish to send a toast/alert to the user, send something meaningful to inform them what went wrong. As an example, instead of "failed" or "failed task", use "failed to upload user data" or "failed to create new user".
Each function will normally return a handful of exception classes that can be used to provide a better toast/alert message. Consulting the documentation for createUserWithEmailAndPassword(email, password) you can see what exceptions are thrown and use instanceof to determine the cause of the problem. For example, if e instanceof FirebaseAuthInvalidCredentialsException was true, you could toast "failed to create new user: invalid email".
While this seems tedious, it will save head-scratching later when a user encounters a problem and sends you a bug report/email about it. These steps will help you find any issues without needing access to logs for trivial problems such as incorrectly filled forms.
Log exceptions
The reason you have no information on what went wrong is because you haven't made use of the exception provided in each onFailure handler (public void onFailure(#NonNull Exception e) { ... }). These handlers provide you with the exception that caused the problem which you can save to the log using Log.e("yourActivityName:yourFunctionName", "short message", e). You can also use e.getMessage() to get information about the thrown error.
In an onComplete(Task<?> task) handler, if task.isSuccessful() returns false, you can find out why it is false by calling Exception e = task.getException() and then log it.
Fail-fast programming
If you ever find that you have an if-else pair where the if section contains lots more code than the else section, it is likely to be a sign that you should flip the condition.
Whilst keeping your code cleaner by using less indentation, it also avoids having to scroll through a long if that probably contains more if and else statements.
For example,
if (!requiredVariable1.isEmpty() && !requiredVariable2.isEmpty()) {
// ...
// many (nested) lines of code
// ...
} else {
Log.e(TAG, "a required variable was empty");
}
if (requiredVariable1.isEmpty() || requiredVariable2.isEmpty()) {
Log.e(TAG, "a required variable was empty");
return;
}
// ...
// many lines of code
// ...
Example
As an example of applying these changes, I have made edits to the code you provided applying fail-fast techniques, simplifying error handling, logging exceptions, using OnSuccessListener and OnFailureListener instead of OnCompleteListener where appropriate,
private void createUserEmailAccount(String email, String password, final String username) {
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(username)) {
Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(#NonNull Task<AuthResult> task) {
currentUser = firebaseAuth.getCurrentUser();
assert currentUser != null;
final String currentUserId = currentUser.getUid();
Map<String, String> userObj = new HashMap<>();
userObj.put("userId", currentUserId);
userObj.put("username", username); // unknown source for variable: username
collectionReference.add(userObj)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
documentReference.get() // why redownload from database? you could just use values of "userObj"
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
progressBar.setVisibility(View.INVISIBLE);
if (!task.isSuccessful()
|| !Objects.requireNonNull(task.getResult()).exists()) {
// show a error message?
return;
}
String name = task.getResult()
.getString("username");
Intent intent = new Intent(CreateAccountActivity.this,
PostJournalActivity.class);
intent.putExtra("username", name);
intent.putExtra("userId", currentUserId);
startActivity(intent);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(CreateAccountActivity.this, "failed to add user data"
, Toast.LENGTH_SHORT).show();
Log.e("CreateAccountActivity", "failed to add user data", e); // log error to logcat
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(CreateAccountActivity.this, "failed to create user"
, Toast.LENGTH_SHORT).show();
Log.e("CreateAccountActivity", "failed to create user", e); // log error to logcat
}
});
}

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.

I am trying to add data to my firebase database by using cloud firestore but it is not adding data neither is it showing any errors

This is the method in which new user get's registered and after registering I use the user ID to add the user data to the database:
public void registerNewEmail(final String email, String password, final TextInputLayout mEmailInputTextLayout, final TextInputLayout mPasswordInputLayout, final String firstName, final String lastName){
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "register user : starting ");
Log.d(TAG, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
assert user != null;
userID = user.getUid();
Log.d(TAG, "UserID: " + userID);
Toast.makeText(mContext,"Sign Up was Successful", Toast.LENGTH_SHORT).show();
sendVerificationEmail();
addNewUser(firstName, lastName, email, userID);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
if(task.getException() instanceof FirebaseAuthUserCollisionException){
mEmailInputTextLayout.setError(mContext.getString(R.string.email_already_used_error));
}
if(task.getException() instanceof FirebaseAuthWeakPasswordException){
mPasswordInputLayout.setError(mContext.getString(R.string.weak_password));
}
mProgressBar.setVisibility(View.GONE);
}
}
});
}
This is the method in which I have used firestore reference to add the data to the firebase database:
/*
* Add new usser to Database
* */
private void addNewUser(String firstName,String lastName,String email,String userID){
String name = firstName + " " + lastName;
User user = new User(name,email);
Log.d(TAG, "addNewUser: " + "userID: " + userID);
mRef.collection(mContext.getString(R.string.DB_users)).document(userID).set(user);
mAuth.signOut();
((Activity)mContext).finish();
}
You can replace mRef.collection(mContext.getString(R.string.DB_users)).document(userID).set(user); with:
db.collection(mContext.getString(R.string.DB_users)).document(userID)
.set(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});

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