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?**
Related
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);
}
}
The current fragment is redirecting to the started activity after i change the data in Firebase. I need to change the visiblity of the button in ManageTeam fragment.The flow of the application is
LoginActivity -> MainActivity -> ManageTeam
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
private MaterialEditText etEmail,etPassword;
private Button btnLogin,btnSignUp;
private FirebaseAuth firebaseAuth;
LinearLayout linearLayout;
private String role;
private User student;
private ProgressDialog progressDialog;
DatabaseReference databaseReference;
ValueEventListener valueEventListener;
private static String user_field = "user";
private static String pwd_field = "pwd";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Paper.init(this);
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setTitle("MTCHY");
progressDialog.setMessage("Login");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
etEmail = (MaterialEditText) findViewById(R.id.etLoginEmail);
etPassword = (MaterialEditText) findViewById(R.id.etLoginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnSignUp = (Button) findViewById(R.id.btnLoginSignUp);
firebaseAuth = FirebaseAuth.getInstance();
linearLayout = (LinearLayout) findViewById(R.id.loginLayout);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String email = etEmail.getText().toString().trim();
String password = etPassword.getText().toString().trim();
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password))
{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Please enter an email and password").setTitle("Warning").setPositiveButton("OK",null);
AlertDialog dialog = builder.create();
dialog.show();
}
else
{
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
databaseReference = FirebaseDatabase.getInstance().getReference();
valueEventListener = databaseReference.child("Users").orderByChild("email").equalTo(email).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Paper.book().write(user_field,etEmail.getText().toString());
Paper.book().write(pwd_field,etPassword.getText().toString());
for(DataSnapshot userDataSnapshot : dataSnapshot.getChildren())
{
student = userDataSnapshot.getValue(User.class);
role = student.getUserRole();
if (role.equals("Player"))
{
progressDialog.dismiss();
startActivity(new Intent(LoginActivity.this,MainActivity.class));
finish();
}
if (role.equals("Captain"))
{
progressDialog.dismiss();
startActivity(new Intent(LoginActivity.this,MainActivity.class));
finish();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(databaseError.getMessage()).setTitle("Database Error").setPositiveButton("OK",null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(e.getMessage()).setTitle("Login Error").setPositiveButton("OK",null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this,SignupActivity.class);
startActivity(intent);
}
});
String papsuser = Paper.book().read(user_field);
String pappwd = Paper.book().read(pwd_field);
System.out.println(papsuser);
System.out.println(pappwd);
if (papsuser != null && pappwd != null)
{
if(!TextUtils.isEmpty(papsuser) && !TextUtils.isEmpty(pappwd))
{
autoLogin(papsuser,pappwd);
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
databaseReference.removeEventListener(valueEventListener);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private BottomNavigationView navigation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AHBottomNavigation bottomNavigation = (AHBottomNavigation) findViewById(R.id.bottom_navigation);
AHBottomNavigationItem item1 = new AHBottomNavigationItem("Home", R.drawable.common_google_signin_btn_icon_dark_focused, R.color.colorBottomNavigationDisable);
AHBottomNavigationItem item2 = new AHBottomNavigationItem("Manage Team", R.drawable.common_google_signin_btn_icon_dark_focused, R.color.colorAccent);
AHBottomNavigationItem item3 = new AHBottomNavigationItem("Setting", R.drawable.common_google_signin_btn_icon_dark_focused,R.color.colorPrimary);
bottomNavigation.addItem(item1);
bottomNavigation.addItem(item2);
bottomNavigation.addItem(item3);
bottomNavigation.setDefaultBackgroundColor(getResources().getColor(R.color.colorBackgroud));
bottomNavigation.setCurrentItem(0);
bottomNavigation.setAccentColor(getResources().getColor(R.color.colorPrimary));
bottomNavigation.setInactiveColor(getResources().getColor(R.color.colorAccent));
bottomNavigation.setForceTint(true);
bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);
AFragment aFragment = new AFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content, aFragment).commit();
bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
#Override
public boolean onTabSelected(int position, boolean wasSelected) {
if(position == 0) {
AFragment aFragment = new AFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content, aFragment).commit();
return true;
}
else if(position == 1 )
{
ManageTeam manageTeam = new ManageTeam();
getSupportFragmentManager().beginTransaction().replace(R.id.content,manageTeam).commit();
return true;
}
return false;
}
});
}
}
ManageTeam.java
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
btn = (Button) getView().findViewById(R.id.btnJohn);
users = FirebaseDatabase.getInstance().getReference("Users");
value = users.orderByChild("email").equalTo("viginesjohn2#gmail.com").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot clubDataSnapshot : dataSnapshot.getChildren())
{
User user = clubDataSnapshot.getValue(User.class);
if (user.getHasTeam() == true)
{
btn.setVisibility(View.GONE);
}
if (user.getHasTeam() == false)
{
btn.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
users.removeEventListener(value);
}
Firebase
My firebase data
UI
Android UI
Based on the UI , the activity will start on Home. After i change the the hasTeam field to true or false in Firebase. The Fragment updates the UI but it will redirect back to Home 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)
Currently, I'm trying to use to update the details from my Firebase Database.However, it gives the classcastexception error. Could anyone help me to solve this problem? Thank you
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.google.online_mobile_flexi_parking, PID: 21533
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String
at com.google.online_mobile_flexi_parking.ChangeEmailPassword$8$1.onDataChange(ChangeEmailPassword.java:243)
at com.google.android.gms.internal.zzakg.zza(Unknown Source)
at com.google.android.gms.internal.zzalg.zzcxk(Unknown Source)
at com.google.android.gms.internal.zzalj$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5028)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
at dalvik.system.NativeStart.main(Native Method)
243 line is phoneAcc.set_IdentityCard(map.get("_IdentityCard"));
ChangeEmailPassword.java
public class ChangeEmailPassword extends AppCompatActivity {
private Button btnChangeEmail, btnChangePassword,
changeEmail, changePassword, back, btnChangePhone, btnChangeCarPlate, changePhone,
changeCarPlate, signOut;
private EditText oldEmail, newEmail, password, newPassword, oldPhone, newPhone, confirmPassword;
private ProgressBar progressBar;
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
DatabaseReference mDatabase;
FirebaseUser user;
private String txtPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_email_password);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getString(R.string.app_name));
setSupportActionBar(toolbar);
//get firebase auth instance
auth = FirebaseAuth.getInstance();
//get current user
user = FirebaseAuth.getInstance().getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference();
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
// user auth state is changed - user is null
// launch login activity
startActivity(new Intent(ChangeEmailPassword.this, TestUser.class));
finish();
}
}
};
btnChangeEmail = (Button) findViewById(R.id.change_email_button);
btnChangePassword = (Button) findViewById(R.id.change_password_button);
btnChangePhone=(Button)findViewById(R.id.change_phone_button);
changeEmail = (Button) findViewById(R.id.changeEmail);
changePassword = (Button) findViewById(R.id.changePass);
changePhone=(Button) findViewById(R.id.changePhone);
//signOut = (Button) findViewById(R.id.sign_out);
back=(Button)findViewById(R.id.btnback1);
oldEmail = (EditText) findViewById(R.id.old_email);
newEmail = (EditText) findViewById(R.id.new_email);
password = (EditText) findViewById(R.id.password);
newPassword = (EditText) findViewById(R.id.newPassword);
confirmPassword=(EditText)findViewById(R.id.confirmpassword);
oldPhone=(EditText)findViewById(R.id.old_phone);
newPhone=(EditText)findViewById(R.id.new_phone);
oldEmail.setVisibility(View.GONE);
newEmail.setVisibility(View.GONE);
password.setVisibility(View.GONE);
newPassword.setVisibility(View.GONE);
confirmPassword.setVisibility(View.GONE);
changeEmail.setVisibility(View.GONE);
changePassword.setVisibility(View.GONE);
oldPhone.setVisibility(View.GONE);
newPhone.setVisibility(View.GONE);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(ChangeEmailPassword.this, TestUser.class));
finish();
}
});
btnChangeEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oldEmail.setVisibility(View.GONE);
newEmail.setVisibility(View.VISIBLE);
password.setVisibility(View.GONE);
newPassword.setVisibility(View.GONE);
confirmPassword.setVisibility(View.GONE);
changeEmail.setVisibility(View.VISIBLE);
changePassword.setVisibility(View.GONE);
changePhone.setVisibility(View.GONE);
oldPhone.setVisibility(View.GONE);
newPhone.setVisibility(View.GONE);
}
});
changeEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
if (user != null && !newEmail.getText().toString().trim().equals("")) {
user.updateEmail(newEmail.getText().toString().trim())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ChangeEmailPassword.this, "Email address is updated. Please sign in with new email id!", Toast.LENGTH_LONG).show();
startActivity(new Intent(ChangeEmailPassword.this, MainActivity.class));
finish();
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(ChangeEmailPassword.this, "Failed to update email!", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
} else if (newEmail.getText().toString().trim().equals("")) {
newEmail.setError("Enter email");
progressBar.setVisibility(View.GONE);
}
}
});
btnChangePassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oldEmail.setVisibility(View.GONE);
newEmail.setVisibility(View.GONE);
password.setVisibility(View.GONE);
newPassword.setVisibility(View.VISIBLE);
confirmPassword.setVisibility(View.VISIBLE);
changeEmail.setVisibility(View.GONE);
changePassword.setVisibility(View.VISIBLE);
changePhone.setVisibility(View.GONE);
oldPhone.setVisibility(View.GONE);
newPhone.setVisibility(View.GONE);
}
});
changePassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
if (user != null && !newPassword.getText().toString().trim().equals("")) {
if (newPassword.getText().toString().trim().length() < 6) {
newPassword.setError("Password too short, enter minimum 6 characters");
progressBar.setVisibility(View.GONE);
} else if (!(newPassword.getText().toString().trim().equals(confirmPassword.getText().toString().trim()))) {
newPassword.setError("Password are not matching");
progressBar.setVisibility(View.GONE);
} else {
user.updatePassword(newPassword.getText().toString().trim())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ChangeEmailPassword.this, "Password is updated, sign in with new password!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(ChangeEmailPassword.this, MainActivity.class));
finish();
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(ChangeEmailPassword.this, "Failed to update password!", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
} else if (newPassword.getText().toString().trim().equals("")) {
newPassword.setError("Enter password");
progressBar.setVisibility(View.GONE);
}
}
});
btnChangePhone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oldEmail.setVisibility(View.GONE);
newEmail.setVisibility(View.GONE);
password.setVisibility(View.GONE);
newPassword.setVisibility(View.GONE);
confirmPassword.setVisibility(View.GONE);
changeEmail.setVisibility(View.GONE);
changePassword.setVisibility(View.GONE);
changePhone.setVisibility(View.VISIBLE);
oldPhone.setVisibility(View.GONE);
newPhone.setVisibility(View.VISIBLE);
}
});
changePhone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
txtPhone = newPhone.getText().toString().trim();
if (!txtPhone.equals("")) {
mDatabase.child(user.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Account phoneAcc=new Account();
Map<String,String> map=(Map)dataSnapshot.getValue();
phoneAcc.set_FullName(map.get("_FullName"));
phoneAcc.set_CarPlate1(map.get("_CarPlate1"));
phoneAcc.set_IdentityCard(map.get("_IdentityCard"));
phoneAcc.set_Phone(txtPhone);
mDatabase.child(user.getUid()).setValue(phoneAcc);
Toast.makeText(ChangeEmailPassword.this, "Phone is updated, sign in with new password!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(ChangeEmailPassword.this, MainActivity.class));
finish();
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else if (txtPhone.equals("")) {
newPhone.setError("Enter phone number");
progressBar.setVisibility(View.GONE);
}
}
});
}
}
Account.java
public class Account {
private String _Phone;
private String _IdentityCard;
private String _FullName;
private String _CarPlate1;
private String _CarPlate2;
private String _CarPlate3;
public Account(){}
public Account(String fullname, String phone, String carplate1, String identitycard)
{
this._Phone=phone;
this._CarPlate1=carplate1;
this._FullName=fullname;
this._IdentityCard=identitycard;
}
public Account(String carplate1,String carplate2,String carplate3)
{
this._CarPlate1=carplate1;
this._CarPlate2=carplate2;
this._CarPlate3=carplate3;
}
public void set_Phone(String _Phone) {
this._Phone = _Phone;
}
public String get_Phone() {
return _Phone;
}
public String get_IdentityCard() {
return _IdentityCard;
}
public void set_IdentityCard(String _IdentityCard){this._IdentityCard=_IdentityCard;}
public String get_FullName() {
return _FullName;
}
public void set_FullName(String _FullName){ this._FullName=_FullName;}
public void set_CarPlate1(String _CarPlate1) {
this._CarPlate1 = _CarPlate1;
}
public String get_CarPlate1() {
return _CarPlate1;
}
public void set_CarPlate2(String _CarPlate2) {
this._CarPlate2 = _CarPlate2;
}
public String get_CarPlate2() {
return _CarPlate2;
}
public void set_CarPlate3(String _CarPlate3) {
this._CarPlate3 = _CarPlate3;
}
public String get_CarPlate3() {
return _CarPlate3;
}
}
It means you can't cast Long type to String directly.Try add "" like
long l = 123;
String str = "" + l;
When you are assigning the long value into string then
long var = 1;
String value = ""+var;
insted of assigning like
String value = var;
It will work.
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.