Password length through Firebase authentication - java

How do I make an error message on password length? through Firebase Authentication for login. If final EditText mpassword.mpassword.setError("Password Must be Between 8 and 15 Characters.");
return;
I have tried to make an if/else statement out of the password length, but that didn't even seem to work right.
Here is the code I have so far.
package com.debatewithus.ui.login;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.debatewithus.MainActivity;
import com.debatewithus.R;
import com.debatewithus.User;
import com.debatewithus.UserLocalStore;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
public class LoginActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState, ClassNotFoundException task) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
Button login;
Button sign_up;
final EditText mail;
final EditText mpassword;
TextView forgotpassword;
final FirebaseAuth auth;
auth = FirebaseAuth.getInstance();
mail = findViewById(R.id.username);
mpassword = findViewById(R.id.Password);
login = findViewById(R.id.login);
sign_up = findViewById(R.id.signup);
forgotpassword = findViewById(R.id.forgotpassword);
login.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
}));
sign_up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email_address = mail.getText().toString().trim();
String password = mpassword.getText().toString().trim();
if (TextUtils.isEmpty(email_address)) {
mail.setError("Email is Required.");
return;
}
if (TextUtils.isEmpty(password)) {
mpassword.setError("Password Required.");
return;
if (!(password.length() < 8 && (password.length() > 15))) {
final EditText mpassword.mpassword.setError("Password Must be Between 8 and 15 Characters.");
return;
}
auth.signInWithEmailAndPassword(email_address, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
startActivity(new Intent(getApplicationContext(), MainActivity.class) {
});
else {
Toast.makeText(LoginActivity.this, "Error!" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
};
});
};
};
});
};
};

You need a logical OR with || instead of a logical AND with &&:
if (!(password.length() < 8 || (password.length() > 15)))
This will evaluate to true if the password length if less than 8 OR greater than 15.

Replace AND with OR , then remove ! . That should do it.
if ((password.length() < 8 || (password.length() > 15))) {

Related

Android App with Firebase [Database Problem]

A few days ago I began programming an app in "Android Studio".
I recently found Firebase which I wanted to use as an database. My problem now is no matter how I write my code nothing will be written into the "Realtime Database". Sometime my App crashes completely and sometimes there is an endless loop of loading.
If there is anyone out there who could help to write into my database
The structure should be the Following:
Users:
--UID:
----age:
----email:
----fullname:
Here is my code, maybe someone can find my misstake.
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
public class RegisterUser extends AppCompatActivity implements View.OnClickListener {
private TextView banner, registerUser;
private EditText editTextFullName, editTextAge, editTextEmail, editTextPassword;
private ProgressBar progressBar;
private FirebaseAuth databaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_user);
databaseAuth = FirebaseAuth.getInstance();
banner = (TextView) findViewById(R.id.banner);
banner.setOnClickListener(this);
registerUser = (Button) findViewById(R.id.registerUser);
registerUser.setOnClickListener(this);
editTextFullName = (EditText) findViewById(R.id.fullName);
editTextAge = (EditText) findViewById(R.id.age);
editTextEmail = (EditText) findViewById(R.id.email);
editTextPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.banner:
startActivity(new Intent(this, MainActivity.class));
break;
case R.id.registerUser:
registerUser();
break;
}
}
private void registerUser() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
String fullName = editTextFullName.getText().toString().trim();
String age = editTextAge.getText().toString().trim();
if (fullName.isEmpty()){
editTextFullName.setError("Bitte ausfüllen.");
editTextFullName.requestFocus();
return;
}
if (age.isEmpty()){
editTextAge.setError("Bitte ausfüllen.");
editTextAge.requestFocus();
return;
}
if (email.isEmpty()){
editTextEmail.setError("Bitte ausfüllen.");
editTextEmail.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
editTextEmail.setError("Bitte eine gültige Email-Adresse angeben.");
editTextEmail.requestFocus();
return;
}
if(password.isEmpty()){
editTextPassword.setError("Bitte ausfüllen.");
editTextPassword.requestFocus();
return;
}
if (password.length() < 6){
editTextPassword.setError("Password muss mindestens aus 6 Zeichen bestehen.");
editTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
databaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
User user = new User(fullName, age, email);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(RegisterUser.this, "Registrierung erfolgreich!", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(RegisterUser.this, "Ein Fehler ist aufgetreten! Versuch es erneut.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
} else {
Toast.makeText(RegisterUser.this, "Ein Fehler ist aufgetreten! Versuch es erneut.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
}```

Firebase User == null all the time

My app uses firebase and it needs to send a verification email to the user after registration before they can login. In my code, the app fails to send the verification email and I found out that the user is always null (while debugging) in line 86/88 of my code. any help would be greaty appreciated.
I've tried retracing my steps back but I couldn't get where i nicked an artery
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import static android.text.TextUtils.isEmpty;
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuthSetUp();
//widgets
TextView mSignUp = (TextView) findViewById(R.id.sign_up_txt);
TextView forgotPassword = (TextView) findViewById(R.id.forgot_password_txt);
Button mSignIn = (Button) findViewById(R.id.sign_in_btn);
final EditText mEmailSignIn = (EditText) findViewById(R.id.sign_in_email);
final EditText mPasswordSignIn = (EditText) findViewById(R.id.sign_in_password);
mSignUp.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
startActivity(intent);
}
}));
//sign in process
mSignIn.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isEmpty(mEmailSignIn.getText().toString()) && !isEmpty(mPasswordSignIn.getText().toString())) {
//showProgressBar();
FirebaseAuth.getInstance().signInWithEmailAndPassword(mEmailSignIn.getText().toString(), mPasswordSignIn.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//hideProgressBar();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, " Authentication Failed!!!", Toast.LENGTH_LONG).show();
//hideProgressBar();
}
});
} else {
Toast.makeText(LoginActivity.this, "Please, Fill All Fields", Toast.LENGTH_LONG).show();
}
}
}));
}
//Setting up Firebase
private void firebaseAuthSetUp() {
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
Log.d("TAG", "CurrentUser: " + user);
if (user != null) {
if(user.isEmailVerified()){
Log.d("TAG", "onAuthStateChanged: signed in: " + user.getEmail());
Toast.makeText(LoginActivity.this, "signed in " + user.getUid(), Toast.LENGTH_LONG).show();
} else{
Toast.makeText(LoginActivity.this, "Please Check Your Email Inbox for Verification Link " + user.getUid(), Toast.LENGTH_LONG).show();
FirebaseAuth.getInstance().signOut();
}
} else {
Toast.makeText(LoginActivity.this, "failed to sign in", Toast.LENGTH_LONG).show();
}
}
};
}
#Override
protected void onStart() {
super.onStart();
FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if (mAuthListener != null) {
FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);
}
}
/*public void showProgressBar(){
mProgressBar.setVisibility(View.VISIBLE);
}
public void hideProgressBar(){
if (mProgressBar.getVisibility() == View.VISIBLE){
mProgressBar.setVisibility(View.INVISIBLE);
}
}*/
}```
Thanks a lot #Praveen and #Alex... figured it out, I made a mistake of signing out the user in the else statement [of the if(user.isEmailVerified()) block in the firebaseAuthSetup() method]. probably wouldn't have gotten it if I didn't retrace from the onComplete()

Code jump to the error statement insist of the creating the account in registration app

I am trying to create a registration Activity in my android application when I compile it runs without and error it seems like there is a logical problem when I run my application instant of creating a new account it jumps to the error code as I have provided my registration activity code in the in method creatnewAccount() in the if statement where I have tried to check whether the rpassword and the password are same. Whenever I run my application and enter the detail and click signup button it jumps to the else statement. Can't understand what's the error and what should I do
package com.nanb.chaton;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import static android.widget.Toast.LENGTH_SHORT;
public class Register extends AppCompatActivity {
private EditText Email, Password, Repassword;
private Button Signup, Login;
private FirebaseAuth mAuth;
private ProgressDialog lodingBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mAuth = FirebaseAuth.getInstance();
rimplemantaion();
sendusertoLogin();
createAccount();
}
private void createAccount() {
Signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createnewAccount();
}
});
}
private void createnewAccount() {
String email = Email.getText().toString();
String password = Password.getText().toString();
String rpassword = Repassword.getText().toString();
if (TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter email i'd ", LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter Password ", LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(rpassword)){
Toast.makeText(this, "Please enter Re-Password ", LENGTH_SHORT).show();
}
if (rpassword == password ){
lodingBar.setTitle("Creating new account");
lodingBar.setMessage("Pleased wait till we creat your account");
lodingBar.setCanceledOnTouchOutside(true);
lodingBar.show();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
sendusertoLogin();
Toast.makeText(Register.this,"Account created succcessfully", Toast.LENGTH_SHORT).show();
lodingBar.dismiss();
}else{
Toast.makeText(Register.this,"Sorry,There is a problem while creating your accout. Please try again later", LENGTH_SHORT).show();
lodingBar.dismiss();
}
}
});
}
else{
Toast.makeText(this, "Password and Re-enter password are not same ", LENGTH_SHORT).show();
}
}
private void sendusertoLogin() {
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent loginIntent = new Intent(Register.this, Login.class);
startActivity(loginIntent);
}
});
}
private void rimplemantaion() {
Email = (EditText) findViewById(R.id.email);
Password = (EditText) findViewById(R.id.password);
Repassword = (EditText) findViewById(R.id.Rpassword);
Signup = (Button) findViewById(R.id.SignUp);
Login = (Button) findViewById(R.id.LogIn);
lodingBar = new ProgressDialog(this);
}
}
Replace this
if (rpassword == password ){
}
else{
Toast.makeText(this, "Password and Re-enter password are not same ", LENGTH_SHORT).show();
}
with this
if (rpassword.equals(password) ){
}
else{
Toast.makeText(this, "Password and Re-enter password are not same ", LENGTH_SHORT).show();
}

Android Studio Sending Variables To Other Activities and Opening Activities At The Same Time

So basically this is my example
Activity A, B, and C.
Say I want to send variables from A to C, and at the same time, open activity B. I I was thinking about multiple intents, but that does not seem to work. Please help with a simple example.
"ACTIVITY A"
package com.example.munaseribrahimewallet;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.content.SharedPreferences;
import android.view.MotionEvent;
import android.view.View;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;
public class SignUpActivity extends AppCompatActivity{
//we will use these constants later to pass the Member name and id to another activity
public static final String EXTRA_EMAIL = "com.example.munaseribrahimewallet.EXTRA_NAME";
private DatePickerDialog mDatePickerDialog;
private static final Pattern PASSWORD_PATTERN =
Pattern.compile("^" +
//"(?=.*[0-9])" + //at least 1 digit
//"(?=.*[a-z])" + //at least 1 lower case letter
//"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white spaces
".{4,}" + //at least 4 characters
"$");
private EditText inputEmail, inputPassword, confirmPassword,editDate; //hit option + enter if you on mac , for windows hit ctrl + enter
private Button btnSignIn, btnSignUp, btnResetPassword;
private ProgressBar progressBar;
private FirebaseAuth mAuth;
DatabaseReference reff;
Member member;
long maxid = 0;
String email, password, cPassword, id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
//Get Firebase auth instance
mAuth = FirebaseAuth.getInstance();
reff = FirebaseDatabase.getInstance().getReference("Members");
btnSignIn = (Button) findViewById(R.id.sign_in_button);
btnSignUp = (Button) findViewById(R.id.sign_up_button);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
confirmPassword = (EditText) findViewById(R.id.password2);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnResetPassword = (Button) findViewById(R.id.btn_reset_password);
editDate = (EditText) findViewById(R.id.editDateBirth);
reff = FirebaseDatabase.getInstance().getReference().child("Member");
reff.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
maxid = (dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
btnResetPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(SignUpActivity.this, ResetPasswordActivity.class));
}
});
btnSignIn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
startActivity(new Intent(SignUpActivity.this, LoginActivity.class));
}
});
btnSignUp.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
cPassword = confirmPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(cPassword)) {
Toast.makeText(getApplicationContext(), "Confirm password!", Toast.LENGTH_SHORT).show();
return;
}
if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
return;
}
if (!(password.matches(cPassword))) {
Toast.makeText(getApplicationContext(), "Password and Confirmation Password are not the same!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//create user
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this,
new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignUpActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(
new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, "Registered successfully. Please check your email for verification", Toast.LENGTH_SHORT).show();
inputEmail.setText("");
inputPassword.setText("");
Intent intent = new Intent(SignUpActivity.this, ProfileActivity.class);
intent.putExtra(EXTRA_EMAIL, email);
startActivity(intent);
finish();
}
}
});
}
}
});
}
});
}
#Override
protected void onResume() {
super.onResume();
progressBar.setVisibility(View.GONE);
}
private boolean validateEmail() {
String emailInput = inputEmail.getText().toString().trim();
if (emailInput.isEmpty()) {
inputEmail.setError("Field can't be empty");
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) {
inputEmail.setError("Please enter a valid email address");
return false;
} else {
inputEmail.setError(null);
return true;
}
}
private boolean validatePassword() {
String passwordInput = inputPassword.getText().toString().trim();
if (passwordInput.isEmpty()) {
inputPassword.setError("Field can't be empty");
return false;
} else if (!PASSWORD_PATTERN.matcher(passwordInput).matches()) {
inputPassword.setError("Password too weak");
return false;
} else {
inputPassword.setError(null);
return true;
}
}
public void addMember() {
//getting the values to save
email = inputEmail.getText().toString().trim();
id = reff.push().getKey();
//checking if the value is provided
if (!TextUtils.isEmpty(email)) {
//getting a unique id using push().getKey() method
//it will create a unique id and we will use it as the Primary Key for our Contact
//Saving the Contact
reff.child(id).setValue(member);
//setting edittext to blank again
inputEmail.setText("");
inputPassword.setText("");
//displaying a success toast
Toast.makeText(this, "Member added", Toast.LENGTH_LONG).show();
} else {
//if the value is not given displaying a toast
Toast.makeText(this, "Please enter a email", Toast.LENGTH_LONG).show();
}
}
private boolean updateMember(String id, String email) {
//getting the specified Contact reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Member").child(id);
//updating Contact
//Member member = new Member(id, email);
dR.setValue(member);
return true;
}
}
"ACTIVITY B"
package com.example.munaseribrahimewallet;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.w3c.dom.Text;
public class PaypalDB extends AppCompatActivity {
private Button btnPaypalLogin;
private EditText editPaypalLogin;
private TextView temail, thomeAddress, tcountry, tcompanyName, tcompanyAddress, tzipcode, tdate, tname, tpaypalEmail;
Member member;
DatabaseReference reff;
String memail, mhomeAddress, mcountry, mcompanyName, mcompanyAddress, mzipcode, mdate, mname, mpaypalEmail, mid;
long maxid = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.paypal_db);
reff = FirebaseDatabase.getInstance().getReference("Members");
editPaypalLogin = (EditText) findViewById(R.id.editPaypalLogin);
btnPaypalLogin = (Button) findViewById(R.id.btnPaypalLogin);
temail= (TextView) findViewById(R.id.txtemail);
thomeAddress= (TextView) findViewById(R.id.txthomeaddress);
tcountry= (TextView) findViewById(R.id.txtcountry);
tcompanyName= (TextView) findViewById(R.id.txtcompanyname);
tzipcode= (TextView) findViewById(R.id.txtzipcode);
tdate= (TextView) findViewById(R.id.txtdate);
tname= (TextView) findViewById(R.id.txtname);
tcompanyAddress = (TextView) findViewById(R.id.txtcompany);
reff = FirebaseDatabase.getInstance().getReference().child("Member");
reff.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
maxid = (dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
btnPaypalLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle extras = getIntent().getExtras();
memail = extras.getString("EXTRA_EMAIL");
mhomeAddress = extras.getString("EXTRA_HOMEADDRESS");
mcountry = extras.getString("EXTRA_SPINNERCOUNTRYTEXT");
mcompanyName = extras.getString("EXTRA_COMPANYNAME");
mcompanyAddress = extras.getString("EXTRA_COMPANYADDRESS");
mzipcode = extras.getString("EXTRA_ZIPCODE");
mdate = extras.getString("EXTRA_DATE");
mname = extras.getString("EXTRA_NAME");
mpaypalEmail = editPaypalLogin.getText().toString();
tcompanyAddress.setText(mcompanyAddress);
tname.setText(mname);
mid = reff.push().getKey();
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Member").child(mid);
reff.child(mid).setValue(member);
member = new Member(mid, memail, mdate, mhomeAddress, mcountry, mcompanyName, mcompanyAddress, mzipcode, mpaypalEmail, mname);
dR.setValue(member);
}
});
}
}
Try to use sharedPreference
Create SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
Storing data as KEY/VALUE pair
editor.putBoolean("key_name1", true); // Saving boolean - true/false
editor.putInt("key_name2", "int value"); // Saving integer
editor.putFloat("key_name3", "float value"); // Saving float
editor.putLong("key_name4", "long value"); // Saving long
editor.putString("key_name5", "string value"); // Saving string
// Save the changes in SharedPreferences
editor.commit(); // commit changes
Get SharedPreferences data
// If value for key not exist then return second param value - In this case null
boolean userFirstLogin= pref.getBoolean("key_name1", true); // getting boolean
int pageNumber=pref.getInt("key_name2", 0); // getting Integer
float amount=pref.getFloat("key_name3", null); // getting Float
long distance=pref.getLong("key_name4", null); // getting Long
String email=pref.getString("key_name5", null); // getting String
Deleting Key value from SharedPreferences
editor.remove("key_name3"); // will delete key key_name3
editor.remove("key_name4"); // will delete key key_name4
// Save the changes in SharedPreferences
editor.commit(); // commit changes
Clear all data from SharedPreferences
editor.clear();
editor.commit(); // commit changes
if my solution is hard for you to understand refer This to get more details

Unable to successfully complete authentication

In the following code, I am trying to open a Login page. User will fill in email and password. When user clicks on login button, checkLogin method is called.
I understand that in the onComplete method, the 1st if block checking success (filling in email, password and clicking login) is not called. I always get the Toast message "Error login" (the else block).
package com.awani.pocketblog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LoginActivity extends AppCompatActivity {
private EditText mLoginEmailField;
private EditText mLoginPasswordField;
private Button mLoginButton;
private Button mNewAccountButton;
private FirebaseAuth mAuth;
private ProgressDialog mProgress;
private DatabaseReference mDatabaseUsers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabaseUsers.keepSynced(true);
mLoginEmailField = (EditText) findViewById(R.id.loginEmailField);
mLoginPasswordField = (EditText) findViewById(R.id.loginPaswordField);
mLoginButton = (Button) findViewById(R.id.loginButton);
mNewAccountButton = (Button) findViewById(R.id.newAccountButton);
mProgress = new ProgressDialog(this);
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkLogin();
}
});
}
private void checkLogin() {
//retrieve the data from database to check if user is logged in correctly
String email = mLoginEmailField.getText().toString().trim();
String password = mLoginPasswordField.getText().toString().trim();
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
mProgress.setMessage("Checking Login...");
mProgress.show();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener < AuthResult > () {
#Override
public void onComplete(#NonNull Task < AuthResult > task) {
//the following if block is never executed....WHY?
if (task.isSuccessful()) {
// Toast.makeText(LoginActivity.this,"hi",Toast.LENGTH_LONG).show();
checkUserExist();
} else {
mProgress.dismiss();
Toast.makeText(LoginActivity.this, "Error Login", Toast.LENGTH_LONG).show();
}
}
});
}
}
private void checkUserExist() {
//retrieving UID
final String user_id = mAuth.getCurrentUser().getUid();
//check if the user with thi UID already exists
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(user_id)) {
Intent mainIntent = new Intent(LoginActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
} else {
Intent setUpIntent = new Intent(LoginActivity.this, SetUpActivity.class);
setUpIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(setUpIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
For authentication with email/password, the user must first be created with createUserWithEmailAndPassword():
Tries to create a new user account with the given email address and
password. If successful, it also signs the user in into the app
This example is provided in Step 4 of the guide for password-based authentication:
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, 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, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
Go to your firebase console, enable sign-in method: Email/Password or Anonymous
If it does not work, please edit your password, maybe it's too short.

Categories

Resources