Firebase signout not performed - android

I am using Firebase Authentification for an Application and I got stuck with an issue.
Firebase FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password) method signs in the user automatically. But I don't want this because I need email verification before log in.
So I implemented a signout when I finish my signup flow. You can find my code below.
My problem is that when I get back to LoginActivity from SignUpActivity, the FirebaseAuthStateListener from LoginActivity detects a user and goes to MainActivity which is something I don't want.
Has anyone ever run through the same issue ?
I am currently using a flag to fix this, but I don't like it at all. I don't get why FirebaseAuth returns a non-null user after I have signed out.
Thanks in advance,
Adrien.
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
// Firebase stuff
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
// Facebook stuff
private CallbackManager mCallbackManager;
private Button mLoginButton;
// Views stuff
private LoginButton mLoginFbButton;
private EditText mEmailTextField;
private EditText mPasswordTextField;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
viewsSetup();
firebaseSetUp();
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onPause() {
super.onPause();
if(mAuthListener != null)mAuth.removeAuthStateListener(mAuthListener);
}
#Override
public void onResume() {
super.onResume();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SIGNUP) {
if (resultCode == RESULT_OK) {
Toast.makeText(getBaseContext(), getString(R.string.you_can_login), Toast.LENGTH_LONG).show();
}
}
onResume();
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void firebaseSetUp() {
mAuth = FirebaseAuth.getInstance();
// Will be notified on login success
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null && !mFromSignup) {
// Login success is handled here and should not be handled anywhere else.
mLoginButton.setEnabled(true);
// Stop the progress dialog
mProgressDialog.dismiss();
toMainActivity();
}
}
};
}
private void signIn(AuthCredential credential) {
// pops up the progress dialog
mProgressDialog = ProgressDialog.show(this, getString(R.string.signing_in), null, true);
// Will be notified when sign in request finish
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// Do not handle authentification success here, on complete
// this will notify the Authentification Listener
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginActivity.this, getString(R.string.login_failed_message),
Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
mLoginButton.setEnabled(true);
}
}
});
}
private void viewsSetup() {
mEmailTextField = (EditText) findViewById(R.id.email);
mPasswordTextField = (EditText) findViewById(R.id.password);
mLoginButton = (Button) findViewById(R.id.login_button);
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginButtonPressed();
}
});
TextView mSignUp = (TextView) findViewById(R.id.create_an_account);
mSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
onPause();
startActivityForResult(intent, REQUEST_SIGNUP);
}
});
mProgressDialog = new ProgressDialog(this);
}
private void loginButtonPressed() {
Log.d(TAG, "Login");
if (!textFieldsFormatValid()) {
Toast.makeText(LoginActivity.this, getString(R.string.check_text_fields),
Toast.LENGTH_SHORT).show();
return;
}
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
mLoginButton.setEnabled(false);
String email = mEmailTextField.getText().toString();
String password = mPasswordTextField.getText().toString();
signIn();
}
private boolean textFieldsFormatValid() {
boolean valid = true;
String email = mEmailTextField.getText().toString();
String password = mPasswordTextField.getText().toString();
if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
mEmailTextField.setError(getString(R.string.ask_valid_email));
valid = false;
} else {
mEmailTextField.setError(null);
}
if (password.isEmpty()) {
mPasswordTextField.setError(getString(R.string.required_field_msg));
valid = false;
} else {
mPasswordTextField.setError(null);
}
return valid;
}
private void toMainActivity() {
// Go to main activity
startActivity(new Intent(LoginActivity.this, MainActivity.class));
// Destroy activity to free memory we won't need it anymore until logout
finish();
}
}
SignUpActivity.java
public class SignUpActivity extends AppCompatActivity {
// Used to determine when user finished signing up
private boolean mFinished = false;
// Firebase stuff
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
// Views stuff
private EditText mEmail;
private EditText mPassword;
private EditText mPasswordConfirm;
private EditText mFullname;
private Button mSignUpButton;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
firebaseSetup();
viewsSetup();
}
#Override
public void onDestroy() {
super.onStop();
if(mAuthListener != null) mAuth.removeAuthStateListener(mAuthListener);
}
private void signUp() {
mProgressDialog = ProgressDialog.show(this, getString(R.string.signing_up), null, true);
if (!textFieldsFormatValid()) {
Toast.makeText(getBaseContext(), getString(R.string.check_text_fields), Toast.LENGTH_LONG).show();
return;
}
mSignUpButton.setEnabled(false);
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// Do not handle authentification success here, on complete
// this will notify the Authentification Listener
if(!task.isSuccessful()) {
Toast.makeText(getBaseContext(), getString(R.string.signup_fail), Toast.LENGTH_LONG).show();
mSignUpButton.setEnabled(true);
mProgressDialog.dismiss();
} else {
mFinished = true;
}
}
});
}
private void firebaseSetup() {
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull final FirebaseAuth firebaseAuth) {
final FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null && !mFinished) {
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(mFullname.getText().toString())
.build();
user.updateProfile(profileUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
firebaseAuth.signOut();
}
});
} else if (mFinished){
// Wait for logout here
firebaseAuth.removeAuthStateListener(this);
mSignUpButton.setEnabled(true);
mProgressDialog.dismiss();
setResult(RESULT_OK, null);
finish();
}
}
};
mAuth.addAuthStateListener(mAuthListener);
}
private void viewsSetup() {
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mPasswordConfirm = (EditText) findViewById(R.id.password_confirm);
mFullname = (EditText) findViewById(R.id.full_name);
mSignUpButton = (Button) findViewById(R.id.signup_button);
TextView mLoginLink = (TextView) findViewById(R.id.to_login);
mSignUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signUpButtonPressed();
}
});
mLoginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
mProgressDialog = new ProgressDialog(this);
}
private void signUpButtonPressed() {
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
if(!textFieldsFormatValid()) {
Toast.makeText(this, R.string.toast_signup_failed, Toast.LENGTH_SHORT);
return;
}
signUp();
}
private boolean textFieldsFormatValid() {
boolean valid = true;
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
String password2 = mPasswordConfirm.getText().toString();
if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
mEmail.setError(getString(R.string.ask_valid_email));
valid = false;
} else {
mEmail.setError(null);
}
if (password.isEmpty() || password.length() < 6 || password.length() > 10) {
mPassword.setError(getString(R.string.password_err_msg));
valid = false;
} else {
mPassword.setError(null);
}
if (password2.isEmpty() || password2.length() < 6 || password2.length() > 10) {
mPasswordConfirm.setError(getString(R.string.password_err_msg));
valid = false;
} else if (!password2.equals(password)) {
mPasswordConfirm.setError(getString(R.string.match_passwords));
valid = false;
} else {
mPasswordConfirm.setError(null);
}
return valid;
}
}

In case someone faces the same problem once, here is how I solved it:
The problem came from the fact I was calling firebaseAuth.signOut() from an asynchronous task (at the completion of user.updateProfile(profile)). And I made an error writing else if(mFinished) and not checking if user == null.
Which led to some cases where I came back to LoginActivity without being signed out.

Related

When my app is destroyed firebase doesn't store my user and it skips the log in page

When I start my app the 1st page is the login, after I successfully log in the new intent brings me to the main menu with my username at the side. When I destroy the app by right the username should be stored at the main menu, but it removes the username and is empty. Hereby I have attached the code for my login.
private EditText PasswdEdit;
private EditText EmailEdit;
private Button LoginBtn;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
mAuth = FirebaseAuth.getInstance();
PasswdEdit = findViewById(R.id.PasswdEdit);
EmailEdit = findViewById(R.id.EmailEdit);
LoginBtn = findViewById(R.id.LoginBtn);
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null)
{
startActivity(new Intent(LogIn.this,MainMenu.class).putExtra("UserName",EmailEdit.getText().toString()));
}
}
};
LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSingIn();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthStateListener);
}
#Override
public void onBackPressed() {
}
private void startSingIn (){
String email = EmailEdit.getText().toString();
String passwd = PasswdEdit.getText().toString ();
if(TextUtils.isEmpty(email) || TextUtils.isEmpty(passwd))
{
Toast.makeText(LogIn.this,"Fields are empty",Toast.LENGTH_LONG).show ();
}
else
{
mAuth.signInWithEmailAndPassword(email,passwd).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(LogIn.this,"Please check your credentials",Toast.LENGTH_LONG).show ();
}
if (task.isSuccessful()) {
FirebaseUser userLogIn = mAuth.getCurrentUser();
}
}
});
}
}
The user was still stored but what I did earlier was I extract the username from the editbox, so when the app is destoryed and restarted the editbox is empty because that page is skipped.
Hereby I have attached the code to overcome this problem.
if (firebaseAuth.getCurrentUser() != null)
{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
startActivity(new Intent(LogIn.this,MainMenu.class).putExtra("UserName",user.getEmail()));
}
if (firebaseAuth.getCurrentUser() == null)
{
}

MVP Architecture

I tried to Refactor the Login Module of the Application Any Mistakes and Suggestions what else should i work on and i should keep in mind
Login Presenter.java
public class LoginPresenter implements LoginInteractor.LoginPresenter {
private LoginInteractor.LoginView loginView;
public LoginPresenter(LoginInteractor.LoginView loginView) {
this.loginView = loginView;
}
#Override
public void CheckIdUserVerified(FirebaseUser currentUser, Context context) {
if (currentUser != null) {
if (currentUser.isEmailVerified()) {
loginView.OnLoginSuccess();
}
}
}
#Override
public void Register() {
loginView.OnRegister();
}
#Override
public void Login(String email,String password,final FirebaseAuth mAuth){
if (email.isEmpty() && password.isEmpty()) {
loginView.OnMessage("password is empty");
return;
} else if (email.isEmpty()) {
loginView.OnMessage("email is empty");
return;
} else if (password.isEmpty()) {
loginView.OnMessage("password is empty");
return;
} else {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
if (mAuth.getCurrentUser().isEmailVerified()) {
loginView.OnLoginSuccess();
} else {
loginView.builderr("Verify","Verify mo to","Verify");
loginView.OnMessage("Failed");
}
}
}});}}}
Should i Use Firebase on the Model part or its ok if its in View
Login View.java
public class LoginView extends AppCompatActivity implements
LoginInteractor.LoginView {
private LoginPresenter loginPresenter;
public Button login;
public TextView register;
EditText editTextEmail, editTextPassword;
FirebaseAuth mAuth;
FirebaseUser currentUser;
ProgressDialog progressDialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Initialize();
loginPresenter.CheckIdUserVerified(currentUser,this);
//LoginButtonOnClick
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginPresenter.Login(editTextEmail.getText().toString(),
editTextPassword.getText().toString(),mAuth);
}
});
//Goto Register Page
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginPresenter.Register();
}
});
}
#Override
public void Initialize() {
loginPresenter = new LoginPresenter(this);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
login = (Button)findViewById(R.id.buttonLogin);
register = (TextView)findViewById(R.id.registertext);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Logging in..");
progressDialog.setCancelable(false);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
}
public void OnVerify(){
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.google.android.gm");
if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
} else {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://mail.google.com/mail/#inbox")));
}
}
public void OnRegister(){
startActivity(new Intent(LoginView.this, RegisterView.class));
}
public void OnMessage(String message){
Toast.makeText(LoginView.this, message, Toast.LENGTH_SHORT).show();
}
public void OnLoginSuccess(){
startActivity(new Intent(LoginView.this, MainActivity.class));
finish();
}
public void builderr(String BulderTitle,String BuilderMessage,String
PositiveButton) {
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(BulderTitle);
builder.setMessage(BuilderMessage);
builder.setInverseBackgroundForced(true);
builder.setPositiveButton(PositiveButton,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
OnVerify();
}});
AlertDialog alert = builder.create();
alert.show();
}}
LoginInteractor
public interface LoginInteractor {
interface LoginView{
void Initialize();
void OnLoginSuccess();
void OnMessage(String message);
void OnRegister();
void builderr(String BulderTitle,String BuilderMessage,String
PositiveButton);
}
interface LoginPresenter{
void CheckIdUserVerified(FirebaseUser currentUser, Context context);
void Login(String email, String password, FirebaseAuth mAuth);
void Register();
}
}
**
If i should put firebase on model any idea that will look like?
i was kinda reasearching and looking for answers but how should i initialize firebase without the oncreate Method?**

MainActivty should lead to LoginActivity but skips it. Leads to MapActivity that should only be visible after login

I seem to have altered something in my code and I can't figure out what it is I need to revert.
I'm building an app that will have a MainActivity that will lead to a loginActivity. However, when the login button is pressed the app is now skipping that and going to a MapActivity that should only be visible to logged in users.
I've checked my MainActivity code and I don't think the problem is there, I think it's the LoginActivity code:
public class ResponderLoginActivity extends AppCompatActivity {
private EditText mEmail, mPassword;
private Button mLogin, mRegistration;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_responder_login);
mAuth = FirebaseAuth.getInstance();
firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
Intent intent = new Intent(ResponderLoginActivity.this, ResponderMapActivity.class);
startActivity(intent);
finish();
return;
}
}
};
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mLogin = (Button) findViewById(R.id.login);
mRegistration = (Button) findViewById(R.id.registration);
mRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(ResponderLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(ResponderLoginActivity.this, "sign up error", Toast.LENGTH_SHORT).show();
} else {
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Responders").child(user_id);
current_user_db.setValue(true);
}
}
});
}
});
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(ResponderLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(ResponderLoginActivity.this, "Sign in error", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthListener);
}
}

Null pointer exception when login fields are empty - Firebase

I have this code where the user enters his credentials and logs in.
public class LoginActivity extends AppCompatActivity {
private static final String TAG = LoginActivity.class.getSimpleName();
private FirebaseAuth mAuth;
private Toolbar mToolbar;
private TextInputEditText mLoginEmail;
private TextInputEditText mLoginPassword;
private Button mLoginBtn;
private Button mForgotPass;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mToolbar = findViewById(R.id.login_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Login");
mAuth = FirebaseAuth.getInstance();
mProgress = new ProgressDialog(this);
mLoginEmail = (TextInputEditText)findViewById(R.id.login_email);
mLoginPassword = (TextInputEditText)findViewById(R.id.login_password);
mLoginBtn = (Button)findViewById(R.id.login_create_btn);
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = mLoginEmail.getText().toString();
String pass = mLoginPassword.getText().toString();
if(!TextUtils.isEmpty(email) || !TextUtils.isEmpty(pass)){
mProgress.setTitle("Logging in");
mProgress.setMessage("Please wait while we check your credentials");
mProgress.setCanceledOnTouchOutside(false);
mProgress.show();
loginUser(email,pass);
}
}
});
mForgotPass = (Button)findViewById(R.id.login_forgot_password);
mForgotPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(LoginActivity.this,ForgotPasswordActivity.class);
startActivity(i);
}
});
}
private void loginUser(final String email, final String pass) {
mAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
mProgress.dismiss();
sendToMain();
} else {
mProgress.hide();
Toast.makeText(LoginActivity.this, "Can not login", Toast.LENGTH_SHORT).show();
Log.d(TAG, String.valueOf(task.getException()));
}
}
});
}
private void sendToMain() {
Intent mainIntent = new Intent(LoginActivity.this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
To achieve a login procedure I call the signInWithEmailAndPassword(email,pass) method as you see above. Just for validation purposes I want to have a toast saying that you should fill both email and password fields. As it is now, I get an exception when I click the login button. How to fix that?
This is the exception.
at com.google.android.gms.common.internal.zzbq.zzgm(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(Unknown Source)
at theo.tziomakas.news.LoginActivity.loginUser(LoginActivity.java:90)
at theo.tziomakas.news.LoginActivity.access$300(LoginActivity.java:22)
at theo.tziomakas.news.LoginActivity$1.onClick(LoginActivity.java:70)
Thanks,
Theo.
Found your error, the following:
if(!TextUtils.isEmpty(email) || !TextUtils.isEmpty(pass))
should be an && and not a ||:
if(!TextUtils.isEmpty(email) && !TextUtils.isEmpty(pass))
You want both to be not null to call your login.

Junit Testing for an Android Activity

Does any one have any experience with creating unit-test for the On Create and OnClick method in java, using Android Studio? I use data from my Firebasedatabase.
I think I have to use Mock-object, but I don't knot where to start.
Under is the code from my class LoginActivity
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mfireBaseAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();
mProgressDialog = new ProgressDialog(this);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
buttonSignIn = (Button) findViewById(R.id.buttonSignIn);
textViewSignUp = (TextView) findViewById(R.id.textViewSignUp);
buttonSignIn.setOnClickListener(this);
textViewSignUp.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v == buttonSignIn){
usersignin();
}
if(v==textViewSignUp){
startActivity(new Intent(this, RegisterActivity.class));
}
}
private void usersignin() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter Email", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter password", Toast.LENGTH_SHORT).show();
return;
}
mProgressDialog.setMessage("Logging in. Please wait...");
mProgressDialog.show();
mfireBaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
mProgressDialog.dismiss();
if(task.isSuccessful()){
getSignedInUserProfile();
}
}
});
}
private void getSignedInUserProfile() {
DatabaseReference reference = mDatabase;//.child("eduback-2feef");
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
userID = firebaseUser.getUid();
reference.child("Users").child(userID).child("User info").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if(user != null) {
// Save if the user is student or prof in shared prefs.
PreferenceHelper helper = new PreferenceHelper(getBaseContext());
helper.setIsStudent(user.isStudent);
checkStudentOrProfessor(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Ups vis error
}
});
}
private void checkStudentOrProfessor(User user) {
Intent i;
if (user.isStudent ) {
i = new Intent(this, MainActivityStudent.class);
} else {
i = new Intent(this, MainActivityProfessor.class);
}
startActivity(i);
}
}
The Mockito mocking framework for Java offers compatibility with Android unit testing.
You can configure mock objects to return some specific value when invoked.
You don't need to test Firebasedatabass.
But you have to make Firebasedatabase wrapper class for yours view
Wrapper class have to include variable(userID, user.isStudent)

Categories

Resources