Android Firebase Error at Creating Users - java

I am trying to make a Firebase Chat application and I can't seem to find the reason why I get the error when I am creating users. In the Firebase Console, Sign-In Method is Enabled on Email/Password.
I have tried:
-Introducing users from the Firebase console, that works
-Introducing legit credentials, so I won't raise up invalid password, username, email errors
-I tried using the code provided by the Android Assistant Firebase, the same error is given to me
Could someone point where I may be wrong?
public class RegisterActivity extends AppCompatActivity {
private TextInputLayout mDisplayName;
private TextInputLayout mEmail;
private TextInputLayout mPassword;
private Button mCreateBtn;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mAuth = FirebaseAuth.getInstance();
mDisplayName = (TextInputLayout) findViewById(R.id.reg_display_name);
mEmail = (TextInputLayout) findViewById(R.id.reg_email);
mPassword = (TextInputLayout) findViewById(R.id.reg_password);
mCreateBtn = (Button) findViewById(R.id.reg_create_btn);
mCreateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String display_name = mDisplayName.getEditText().getText().toString();
String email = mEmail.getEditText().getText().toString();
String password = mPassword.getEditText().getText().toString();
register_user(display_name, email, password);
}
});
}
private void register_user(String display_name, String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Intent mainIntent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(mainIntent);
finish();
}
else {
Toast.makeText(RegisterActivity.this, "You got some error with creating the new user.", Toast.LENGTH_LONG).show();
}
}
});
}
}

auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
if (!task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "Authentication failed." + task.getException(), Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
finish();
}
}
});
Try this one I think you have forgotten addOnCompleteListener(Executor executor, OnCompleteListener listener), the Executor determines the thread that will be used to invoke the listener.

Related

Cannot resolve method 'setTimestampsInSnapshotsEnabled' in 'Builder'

I am trying to create a register activity to allow a user to register however I keep getting the error:
Cannot resolve method 'setTimestampsInSnapshotsEnabled' in 'Builder'"
It's only the section which has the setTimestampsInSnapshotsEnabled that is giving me the issue. Do I need an implementation?
Here is my Java code:
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener
{
private static final String TAG = "RegisterActivity";
//widgets
private EditText mEmail, mPassword, mConfirmPassword;
private ProgressBar mProgressBar;
//vars
private FirebaseFirestore mDb;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mEmail = (EditText) findViewById(R.id.input_email);
mPassword = (EditText) findViewById(R.id.input_password);
mConfirmPassword = (EditText) findViewById(R.id.input_confirm_password);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
findViewById(R.id.btn_register).setOnClickListener(this);
mDb = FirebaseFirestore.getInstance();
hideSoftKeyboard();
}
/**
* Register a new email and password to Firebase Authentication
* #param email
* #param password
*/
public void registerNewEmail(final String email, String password){
showDialog();
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
if (task.isSuccessful()){
Log.d(TAG, "onComplete: AuthState: " + FirebaseAuth.getInstance().getCurrentUser().getUid());
//insert some default data
User user = new User();
user.setEmail(email);
user.setUsername(email.substring(0, email.indexOf("#")));
user.setUser_id(FirebaseAuth.getInstance().getUid());
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setTimestampsInSnapshotsEnabled(true)
.build();
mDb.setFirestoreSettings(settings);
FirebaseFirestoreSettings newUserRef = mDb
.collection(getString(R.string.collection_users))
.document(FirebaseAuth.getInstance().getUid());
newUserRef.set(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
hideDialog();
if(task.isSuccessful()){
redirectLoginScreen();
}else{
View parentLayout = findViewById(android.R.id.content);
Snackbar.make(parentLayout, "Something went wrong.", Snackbar.LENGTH_SHORT).show();
}
}
});
}
else {
View parentLayout = findViewById(android.R.id.content);
Snackbar.make(parentLayout, "Something went wrong.", Snackbar.LENGTH_SHORT).show();
hideDialog();
}
// ...
}
});
}
/**
* Redirects the user to the login screen
*/
private void redirectLoginScreen(){
Log.d(TAG, "redirectLoginScreen: redirecting to login screen.");
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
private void showDialog(){
mProgressBar.setVisibility(View.VISIBLE);
}
private void hideDialog(){
if(mProgressBar.getVisibility() == View.VISIBLE){
mProgressBar.setVisibility(View.INVISIBLE);
}
}
private void hideSoftKeyboard(){
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_register:{
Log.d(TAG, "onClick: attempting to register.");
//check for null valued EditText fields
if(!isEmpty(mEmail.getText().toString())
&& !isEmpty(mPassword.getText().toString())
&& !isEmpty(mConfirmPassword.getText().toString())){
//check if passwords match
if(doStringsMatch(mPassword.getText().toString(), mConfirmPassword.getText().toString())){
//Initiate registration task
registerNewEmail(mEmail.getText().toString(), mPassword.getText().toString());
}else{
Toast.makeText(RegisterActivity.this, "Passwords do not Match", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(RegisterActivity.this, "You must fill out all the fields", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
}
If I look at the current documentation for FirebaseFirestoreSettings.Builder, I don't see any setTimestampsInSnapshotsEnabled method. So that probably explains the error message: you're trying to call a method that doesn't exist.
My guess is that your code was meant for an older version of the SDK when the method did exist. Since it doesn't exist anymore now, you either have to use the version of the SDK that the code was made for, or remove the call.
Update: it looks like timestampsInSnapshotsEnabled was removed in version 22 of the Android SDK for Firestore back in October 2020.

Can we show the login information made with the firebase authentication system as textview in the application?

I have created a login-register system by using Firebase auth. Now I want to show the registration information (name, email, phone) in my app. I want to reflect the registration information to text view but I couldn't find the way to do that.
Registration class:
public class RegisterActivity extends AppCompatActivity {
EditText mName, mEmail, mPassword, mPhone;
Button mRegisterButton;
TextView mLoginButton;
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mName = findViewById(R.id.userName);
mEmail = findViewById(R.id.userMail);
mPassword = findViewById(R.id.userPassword);
mPhone = findViewById(R.id.userPhone);
mRegisterButton = findViewById(R.id.register_button);
mLoginButton = findViewById(R.id.goToLogin);
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser() != null){
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
if(TextUtils.isEmpty(email))
{
mEmail.setError("Email is required");
return;
}
if(TextUtils.isEmpty(password))
{
mPassword.setError("Password is required");
return;
}
if(password.length() < 0)
{
mPassword.setError("Password Must Be >= 6 Characters");
return;
}
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(RegisterActivity.this, "User Created.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
Log.d(TAG, "createUserWithEmail:success");
FirebaseUser user = firebaseAuth.getCurrentUser();
}else{
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(RegisterActivity.this, "Error!" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(),LoginActivity.class));
}
});
}
}
Assuming that you have a TextView added in your layout, especially added to display the data, then right after the following line of code:
FirebaseUser user = firebaseAuth.getCurrentUser();
Add these lines:
String name = user.getDisplayName();
String email = user.getEmail();
TextView textView = findViewById(R.id.textViewId);
String text = name + "/" + email;
textView.setText(text);
Please also note that when you are using email and password authentication the phone number doesn't exist. So if you try to use it, you'll get null.
Kotlin code below;
fun onCreate(savedInstanceState: Bundle) {
val curreentUser = FirebaseAuth.getInstance().currentUser
val name = currentUser?.displayName
val email = currentUser?.email
val phone = currentUser?.phoneNumber
val textView = findViewById(R.id.your_text_view_id)
textView.text = "$name, $email, $phone"
}

User logs out every time app is closed - Firebase Authentication - Android Studio (Java)

My android application uses firebase authentication. Once the user logs in and is in the app, getCurrentUser() is not null, which is good. But, once the user closes the app, they don't stay logged in.
Here's my code:
public class login extends AppCompatActivity {
EditText email, password;
Button signIn, toSignUp;
FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
FirebaseUser firebaseUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = findViewById(R.id.insertemail);
password = findViewById(R.id.checkpassword);
signIn = findViewById(R.id.signIn);
toSignUp = findViewById(R.id.toSignUp);
mFirebaseAuth = FirebaseAuth.getInstance();
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser mFireBaseUser = mFirebaseAuth.getCurrentUser();
if (mFirebaseAuth.getCurrentUser() != null) {
Toast.makeText(login.this, "You are logged in!", Toast.LENGTH_SHORT).show();
Intent inte = new Intent(login.this, MapsActivity.class);
startActivity(inte);
} else {
Toast.makeText(login.this, "Please log in", Toast.LENGTH_SHORT).show();
}
}
};
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String em = email.getText().toString();
String pass = password.getText().toString();
if (em.isEmpty()) {
email.setError("Please enter your Email ID");
email.requestFocus();
} else if (pass.isEmpty()) {
password.setError("Please enter you Password");
password.requestFocus();
} else if (em.isEmpty() && pass.isEmpty()) {
Toast.makeText(login.this, "Fields are empty!", Toast.LENGTH_SHORT).show();
} else if (!(em.isEmpty() && pass.isEmpty())) {
mFirebaseAuth.signInWithEmailAndPassword(em, pass).addOnCompleteListener(login.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(login.this, "Log in Failed. Please try again!", Toast.LENGTH_SHORT).show();
} else {
Intent inten = new Intent(login.this, MapsActivity.class);
startActivity(inten);
}
}
});
} else {
Toast.makeText(login.this, "Error Occurred!", Toast.LENGTH_SHORT).show();
}
}
});
toSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(login.this, signup.class);
startActivity(intent);
}
});
}
}
Why is mFirebaseAuth.getCurrentUser() null every time the app is closed?
Thank you for your help in advance!
The current user is null on a cold start of the app because it takes time (and network connectivity) to determine if that user is valid. Firebase isn't going to block the launch of the app to determine if the user is valid. It's going to let your code run ASAP. The AuthStateListener callback you provide will be invoked whenever the SDK is sure that the user is valid.
If you want to know for sure if the user is signed in or signed out at the time the app is launched, you should wait for the first callback to the listener. Until then, the sign-in status of the user is unknown, and it probably makes sense to show a spinner or some other wait screen until then.

User credentials are not getting stored in firebase database

While registering for user, it is getting failed and gives exception in logcat as
" I/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzaq#1a8a2b0 "
All the correct and updated dependencies are implemented.....
While clicking on signup button on android studio it is getting failed and gives the message as "Failed while registering, An internal error has occurred [7 :]"
public class RegistrationActivity extends AppCompatActivity
{
private EditText email;
private EditText password;
private TextView signIn;
private Button registerBtn;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
firebaseAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
email = findViewById(R.id.email_register);
password = findViewById(R.id.password_register);
registerBtn = findViewById(R.id.btn_register);
signIn = findViewById(R.id.sign_in_txt);
registerBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
String myEmail = email.getText().toString().trim();
String myPass = password.getText().toString().trim();
if (TextUtils.isEmpty(myEmail))
{
email.setError("This field is required.");
return;
}
if (TextUtils.isEmpty(myPass))
{
password.setError("This field is required.");
return;
}
progressDialog.setMessage("Registering please wait...");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(myEmail, myPass).addOnCompleteListener(RegistrationActivity.this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if (task.isSuccessful())
{
startActivity(new Intent(getApplicationContext(), HomeActivity.class));
Toast.makeText(getApplicationContext(), "Successfully Registered...", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
else
{
Toast.makeText(getApplicationContext(), "Failed while registering..." + task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}
});
}
});
signIn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
}
}

How to register user into firebase registration?

I am going to insert my email and password into Firebase Authentication. However, the code that I found on the Internet does not work for me? Below is the code and when I click next button, it goes back to the previous page too, it does not proceed with the next page?
public void completeRegis() {
username1 = username.getText().toString().trim();
email1 = email.getText().toString().trim();
psd1 = psd.getText().toString().trim();
psd2 = reconpsd.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(email1, psd1)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//start profile activity here
User user = new User(username1, email1,psd1);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(RoleInfo1.this, "Registration successful.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(RoleInfo1.this, HomePage.class ));
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(RoleInfo1.this, "Database not created", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
} else {
Toast.makeText(RoleInfo1.this, "Registration not successful, please try again.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
private void initializeUI() {
username = findViewById(R.id.usernameregister);
email = findViewById(R.id.emailregister);
psd = findViewById(R.id.psdregister);
reconpsd = findViewById(R.id.reconpsdregister);
progressBar = findViewById(R.id.progressBar);
}
}
I am very new to android but I recently made a signUp page successfully.
declare a firebase auth instance
private FirebaseAuth mAuth;
private EditText mName, mEmailField, mConfirmPass, mNewPass;
then in onCreate() I declared them as
mName = (EditText) findViewById(R.id.eName);
mEmailField = (EditText) findViewById(R.id.fieldEmail);
mConfirmPass = (EditText) findViewById(R.id.fieldConfirm);
mNewPass = (EditText) findViewById(R.id.fieldNew);
mAuth = FirebaseAuth.getInstance();
I added a button in the authentication page for signup. Clicking on it starts the signUp procedure. This is done in onCreate() method
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startSignUp();
}
});
Then I declare the startSignUp() method as below
public void startSignUp(){
String name = mName.getText().toString();
String email = mEmailField.getText().toString();
String newPass = mNewPass.getText().toString();
String conPass = mConfirmPass.getText().toString();
if(TextUtils.isEmpty(name) || TextUtils.isEmpty(email) || TextUtils.isEmpty(newPass) || TextUtils.isEmpty(conPass)){
Toast.makeText(SignUp.this, "Fields Empty" , Toast.LENGTH_LONG).show();
}
mAuth.createUserWithEmailAndPassword(email,newPass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(! task.isSuccessful()){
Toast.makeText(SignUp.this, "SignUp Failed", Toast.LENGTH_LONG).show();
}else {
openAuthetication();
}
}
});
}
}
If signUp is successful, it will go back to the authentication page for signing in. This is done in the openAuthetication() method.
public void openAuthetication(){
Intent intent = new Intent(this, Authetication.class);
startActivity(intent);
}

Categories