I am beginner and building register and login activities using firebase
I show login activity first. It has clickable text view which reads as "No account? Click here to register" when clicked it starts registration activity and allows user to register but after registering it needs to start login activity but it is not happening
Below is Registration.java
public class Registration extends AppCompatActivity {
private EditText etname, etmail, etpass;
private Button btnreg;
FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
etname = (EditText) findViewById(R.id.etRemail);
etmail = (EditText) findViewById(R.id.etRemail);
etpass = (EditText) findViewById(R.id.etRpass);
btnreg = (Button) findViewById(R.id.btnRreg);
progressDialog = new ProgressDialog(this);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() != null) {
Intent in = new Intent(getApplicationContext(), MainActivity.class);
startActivity(in);
finish();
}
}
public void user_reg_info(View view) {
String uname = etname.getText().toString();
String uemail = etmail.getText().toString();
String upass = etpass.getText().toString();
try {
if (uname.isEmpty() || uname.trim().equals("")) {
etname.setError("Name cannot be empty!");
return;
}
if (uemail.isEmpty() || uemail.trim().equals("")) {
etmail.setError("Email cannot be empty!");
return;
}
if (upass.isEmpty() || upass.equals("")) {
etpass.setError("Password cannot be empty!");
return;
}
progressDialog.setMessage("Registering..please wait!");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(uemail, upass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
Toast.makeText(Registration.this, "Registration successful", Toast.LENGTH_LONG).show();
Intent i = new Intent(Registration.this,Login.class);
startActivity(i);
finish();
} else {
Log.e("Error", task.getException().toString());
Toast.makeText(Registration.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
On click of register button it directly starts MainActivity
Below is Login.java
public class Login extends AppCompatActivity {
private EditText etmail,etpass;
private TextView clktoreg;
private ImageView imgLogin;
private Button btnLog;
private ProgressDialog progressDialog;
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etmail = (EditText) findViewById(R.id.eTLemail);
etpass = (EditText) findViewById(R.id.eTLpass);
clktoreg = (TextView) findViewById(R.id.click_2_reg);
imgLogin = (ImageView) findViewById(R.id.imgLogin);
btnLog = (Button) findViewById(R.id.btnLogin);
progressDialog = new ProgressDialog(this);
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser()!=null){
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
}
public void login_user(View view) {
String email = etmail.getText().toString();
String pass = etpass.getText().toString();
try {
if (email.isEmpty() || email.trim().equals("")) {
etmail.setError("E-mail cannot be empty!");
return;
}
if (pass.isEmpty() || pass.trim().equals("")) {
etpass.setError("Password cannot be empty!");
return;
} else {
progressDialog.setMessage("Logging in..please wait!");
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(email, pass)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
Intent in = new Intent(getApplicationContext(), MainActivity.class);
startActivity(in);
finish();
} else {
etmail.setError("Check email ID");
etpass.setError("Check password");
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void not_registered(View view) {
Intent in = new Intent(this,Registration.class);
startActivity(in);
}
}
I explain what your app does.
You register the user then the user is not null anymore, login activity is open and you have that in login activity:
if(firebaseAuth.getCurrentUser()!=null){
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
Because the user is not null anymore when the login activity start and reach this condiction the mainActivity starts.
Related
I am new to android so there is some problem when i run the code to register or login with firebase authentication i can run the code but when i execute the signup function after pressing the register button it takes a lot time to register 1 account.
`
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
private FirebaseAuth mAuth;
private Button btn_register;
private EditText et_name, et_age, et_email, et_password;
private ProgressBar ProgressBar;
private TextView name_project;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mAuth = FirebaseAuth.getInstance();
name_project = (TextView) findViewById(R.id.name_project);
name_project.setOnClickListener(this);
btn_register = (Button) findViewById(R.id.btn_register);
btn_register.setOnClickListener(this);
et_name = (EditText) findViewById(R.id.et_name);
et_age = (EditText) findViewById(R.id.et_age);
et_email = (EditText) findViewById(R.id.et_email);
et_password = (EditText) findViewById(R.id.et_password);
ProgressBar = (ProgressBar) findViewById(R.id.progressBar);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.name_project:
startActivity(new Intent(this, MainActivity.class));
break;
case R.id.btn_register:
registerUser();
break;
}
}
private void registerUser() {
String email = et_email.getText().toString().trim();
String password = et_password.getText().toString().trim();
String name = et_name.getText().toString().trim();
String age = et_age.getText().toString().trim();
if (name.isEmpty()) {
et_name.setError("Please enter your full name");
et_name.requestFocus();
return;
}
if (age.isEmpty()) {
et_age.setError("Please enter your age");
et_age.requestFocus();
return;
}
if (email.isEmpty()) {
et_email.setError("Please enter your email");
et_email.requestFocus();
return;
}
if (password.isEmpty()) {
et_password.setError("Please enter your password");
et_password.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
et_email.setError("Please enter valid email");
et_email.requestFocus();
return;
}
if (password.length() < 6) {
et_password.setError("The length of password should be more than 6 letters");
et_password.requestFocus();
return;
}
ProgressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(intent);
finish();
Toast.makeText(RegisterActivity.this, "Registered successfully", Toast.LENGTH_SHORT).show();
ProgressBar.setVisibility(View.GONE);
} else {
Toast.makeText(RegisterActivity.this, "Registered fail", Toast.LENGTH_SHORT).show();
ProgressBar.setVisibility(View.GONE);
}
}
});
}
}
enter image description here`
I have tried many methods but registration takes a long time.
Please make sure you have enabled the Email/Password provider in the Authentification tab on the Firebase console.
I am developing an app on android studio and need to redirect clients and personal trainers to two different activities based on their role. Personal Trainers need to be directed to PTNoticeboardActivity and clients to NoticeboardActivity. Any suggestion on how to do this, here is my login code:
public class MainActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
}
public void loginUser(View View){
String email = ((EditText) findViewById(R.id.editText_Log_email)).getText().toString();
String password = ((EditText) findViewById(R.id.editText_Log_password)).getText().toString();
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter email", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)){
Toast.makeText(this, "Please Enter Password", Toast.LENGTH_LONG).show();
return;
}
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_LONG).show();
// startActivity(new Intent(getApplicationContext(), NoticeBoardActivity.class));
// finish();
} else {
Toast.makeText(MainActivity.this, "Login Unsuccessful", Toast.LENGTH_LONG).show();
}
}
});
}
}
Here is my register activity code below:
public class RegisterActivity extends AppCompatActivity {
EditText txt_fullname, txt_email, txt_mobilenumber, txt_repassword,
txt_password;
Button btn_register;
RadioButton radioJobClient, radioJobPT;
DatabaseReference databaseReference;
FirebaseDatabase firebaseDatabase;
String job ="";
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
txt_fullname = (EditText) findViewById(R.id.editText_fullname);
txt_email = (EditText) findViewById(R.id.editText_UserEmail);
txt_password = (EditText) findViewById(R.id.editText_Password);
txt_repassword = (EditText) findViewById(R.id.editText_rePassword);
txt_mobilenumber = (EditText) findViewById(R.id.mobilenumber);
btn_register = (Button) findViewById(R.id.button_reg);
radioJobClient = (RadioButton) findViewById(R.id.radio_Client);
radioJobPT = (RadioButton) findViewById(R.id.radio_PersonalTrainer);
databaseReference = FirebaseDatabase.getInstance().getReference("User");
// new code
firebaseAuth = FirebaseAuth.getInstance();
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String fullname = txt_fullname.getText().toString();
final String email = txt_email.getText().toString();
final String mobilenumber = txt_mobilenumber.getText().toString();
final String password = txt_password.getText().toString();
final String rePassword = txt_repassword.getText().toString();
if (radioJobClient.isChecked()){
job = "Client";
}
if (radioJobPT.isChecked()){
job = "PT";
}
if (TextUtils.isEmpty(email)){
Toast.makeText(RegisterActivity.this, "Please enter Email", Toast.LENGTH_LONG).show();
}
if (TextUtils.isEmpty(fullname)){
Toast.makeText(RegisterActivity.this, "Please enter fullname", Toast.LENGTH_LONG).show();
}
if (TextUtils.isEmpty(password)){
Toast.makeText(RegisterActivity.this, "Please enter password", Toast.LENGTH_LONG).show();
}
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
User user = new User(
fullname,
email,
mobilenumber,
password,
job
);
FirebaseDatabase.getInstance().getReference("User")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(RegisterActivity.this, "Registration Complete", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
} else {
Toast.makeText(RegisterActivity.this, "Registration Unsuccessful", Toast.LENGTH_LONG).show();
}
// ...
}
});
}
});
}
public void goLogin (View view){
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}
}
Database structure:
This is the most efficient way to do it:
When your user has created an account, create a child node in the firebase database as role with value as per the user. [could be client or personal trainer]
Then when your activity starts, fetch the value from the database like this:
First of all add a LOGIN BUTTON toyour login activity. When user presses that then only the login thing will take place.
Here is your modified MainActivity.java:
public class MainActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
String userRole;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
btnLogin = findViewById(R.id.btn_login_resource);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = ((EditText) findViewById(R.id.editText_Log_email)).getText().toString();
String password = ((EditText) findViewById(R.id.editText_Log_password)).getText().toString();
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter email", Toast.LENGTH_LONG).show();
return;
}
else if (TextUtils.isEmpty(password)){
Toast.makeText(this, "Please Enter Password", Toast.LENGTH_LONG).show();
return;
}
else{
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_LONG).show();
jobRef = FirebaseDatabase.getInstance().getReference().child("User").child(pAuth.getCurrentUser().getUid()).child("job");
jobRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
userRole = dataSnapshot.getValue().toString();
if(userRole.equals("Client")){
startActivity(new Intent(MainActivity.this, NoticeboardActivity.class);
}
else {
startActivity(new Intent(MainActivity.this, PTNoticeboardActivity.class);
}
}catch (Throwable e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.toString(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(MainActivity.this, "Login Unsuccessful", Toast.LENGTH_LONG).show();
}
}
});
}
}
}
});
.
Now one thing to care about is that anyone can reverse-engineer this code and illegally can get access to the data. So make sure the data in each activity is hosted in Firebase and you have set the appropriate firebase rules. If you want me to elaborate please let me know in the comments down below.
So my concern is that I am using Shared Preference to store Name in android and can also retrieve the same when logged in again.But, when some other person logs in from the same device, still the name stored is of the previous user. How can I change this and fetch the value of the New user name from firebase? P.S I am new to Android
Following is my code for Manual Login:-
public class ManualLogin extends AppCompatActivity implements View.OnClickListener{
private Button buttonRegister;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignup;
private EditText editTextName;
DatabaseReference databaseUsers;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
private static final String TAG = "FACELOG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_login);
databaseUsers = FirebaseDatabase.getInstance().getReference("Users");
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser()!=null){
//profile activity here
finish();
startActivity(new android.content.Intent(getApplicationContext(), AccountActivity.class));
}
progressDialog = new ProgressDialog(this);
buttonRegister = (Button)findViewById(R.id.buttonRegister);
editTextEmail = (EditText)findViewById(R.id.editTextEmail);
editTextPassword = (EditText)findViewById(R.id.editTextPassword);
editTextName = (EditText)findViewById(R.id.editTextName);
textViewSignup = (TextView)findViewById(R.id.textViewSignup);
buttonRegister.setOnClickListener(this);
textViewSignup.setOnClickListener(this);
}
public void registerUser() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
final String name = editTextName.getText().toString().trim();
if(!TextUtils.isEmpty(name)) {
String id = databaseUsers.push().getKey();
Users users = new Users(id, name);
databaseUsers.child(id).setValue(users);
//Toast.makeText(this, "User Created", Toast.LENGTH_SHORT).show();
}else{
//email is empty
Toast.makeText(this, "Enter Name", Toast.LENGTH_SHORT).show();
//stop function execution
return;
}
if(TextUtils.isEmpty(email)){
//email is empty
Toast.makeText(this, "Enter Email id", Toast.LENGTH_SHORT).show();
//stop function execution
return;
}
if(TextUtils.isEmpty(password)){
//password is empty
Toast.makeText(this, "Enter Password", Toast.LENGTH_SHORT).show();
//stop function execution
return;
}
//if validations are fine
//show progressBar
progressDialog.setMessage("Registering User...");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//user is successfully registered & logged in
//profile activity here
finish();
startActivity(new android.content.Intent(getApplicationContext(), AccountActivity.class));
userProfile();
Toast.makeText(ManualLogin.this, "Registered Successfully", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(ManualLogin.this, "Failed to Register", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
SharedPreferences sharedPref = getSharedPreferences("userName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", editTextName.getText().toString());
editor.commit();
//Toast.makeText(ManualLogin.this, "Name Saved", Toast.LENGTH_SHORT).show();
}
});
}
//set User Display name
private void userProfile(){
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(editTextName.getText().toString().trim()).build();
user.updateProfile(profileUpdate).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.d("Testing", "User Profile Updated");
}
}
});
}
}
#Override
public void onClick(View v) {
if(v == buttonRegister){
registerUser();
}
if(v == textViewSignup){
//open login activity
finish();
startActivity(new android.content.Intent(this, LoginActivity.class));
}
}
}
Below is the code for AccountActivity:-
public class AccountActivity extends AppCompatActivity {
private Button logout;
private TextView textViewUserName;
private FirebaseAuth mAuth;
private FirebaseAuth firebaseAuth;
private String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
logout = (Button)findViewById(R.id.logout);
textViewUserName = (TextView)findViewById(R.id.textViewUserName);
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this, LoginActivity.class));
}
FirebaseUser sname = firebaseAuth.getCurrentUser();
textViewUserName.setText("Welcome "+ sname.getDisplayName());
SharedPreferences sharedPref = getSharedPreferences("userName", Context.MODE_PRIVATE);
String name = sharedPref.getString("name", "");
textViewUserName.setText("Welcome "+ name);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
LoginManager.getInstance().logOut();
updateUI();
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
updateUI();
}
}
private void updateUI() {
Toast.makeText(this, "You have Logged out", Toast.LENGTH_SHORT).show();
Intent accountIntent = new Intent(this, MainActivity.class);
startActivity(accountIntent);
finish();
}
}
when you login that time store data into sharedpreference like below
private void saveData(String value){
SharedPreferences sharedPreferences=getSharedPreferences("MyData",MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("User",value);
editor.commit();
}
In read new user data into firebase database.
private void readData() {
// define only root node.
mFirebaseDatabase.child("User").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
User user = dataSnapshot.getValue(User.class);
mEtPwd.setText(user.pwd);
mEtName.setText(user.name);
mEtEmail.setText(user.email);
saveData(user.name);
// }
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled", databaseError.toException());
}
});
}
Everything looks fine to me, I just want to register a user in firebase but it doesn't work. Here is my activity:
public class SignUp extends Activity {
Button signup1;
EditText email1, password1, password2;
FirebaseAuth firebaseAuth;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
//Instantiate the FirebaseAuth object
firebaseAuth = FirebaseAuth.getInstance();
signup1 = (Button) findViewById(R.id.signup);
// Setting the listener for button
signup1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
register();
}
});
email1 = (EditText) findViewById(R.id.email);
password1 = (EditText) findViewById(R.id.password1);
password2 = (EditText) findViewById(R.id.password2);
progressDialog = new ProgressDialog(this);
}
public void register() {
String email = email1.getText().toString().trim();
String pass1 = password1.getText().toString().trim();
String pass2 = password2.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please Enter an Email", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(pass1)) {
Toast.makeText(this, "Please Enter Password", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(pass2)) {
Toast.makeText(this, "Please Enter Password Again", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.equals(pass1, pass2)) {
progressDialog.setMessage("Registering....!");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(email, pass2).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(SignUp.this,"SignUp Successfully", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(SignUp.this, "SignUp Failed... Try Again", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
});
}
else {
Toast.makeText(this, "Password does not Match", Toast.LENGTH_SHORT).show();
return;
}
}
}
The application stucks when it goes into "createUserWithEmailAndPassword".
Use try-catch for exception.
For example createUser... method is null and catch it and resolve.
I am stuck in a loop here.
Users can log in with their FB account. The app creates a Firebase user w/ the same info.
With the launcher activity (LoginActivity), if it detects an user is already logged in, it redirects them to their profile fragment.
However, on the profile fragment, I click the log off button and redirect
them to the Login page. This is where the cycle begins.
From code snippets and official Firebase doc, I am using .unauth();. However, my logcat still shows the user is logged in. I've also tried using the Facebook SDK method of LoginManager, but that hasn't worked either.
LogOut method (in MainFrag)
public void LogOut(){
Log.d(TAG, "CHECK #2: USER SIGNED OUT");
getActivity().getIntent().removeExtra("user_id");
getActivity().getIntent().removeExtra("profile_picture");
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
Log.d(TAG, "signed out" + mUser.getUid());
// mAuth.unauth();
Intent intent = new Intent(getActivity().getApplicationContext(),
LoginActivity.class);
myFirebaseRef.unauth();
LoginManager.getInstance().logOut();
startActivity(intent);
Log.d(TAG, "CHECK 3: FINISIHED SIGNED OUT");
Log.d(TAG, "onAuthStateChanged:signed_out");
}
LoginActivity
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "AndroidBash";
public User user;
private EditText email;
private EditText password;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private ProgressDialog mProgressDialog;
private DatabaseReference mDatabase;
//Add YOUR Firebase Reference URL instead of the following URL
private Firebase mRef=new Firebase("https://fitmaker-ee2c0.firebaseio.com/");
//FaceBook callbackManager
private CallbackManager callbackManager;
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "CHECK - FB SIGN IN - USER IS LOGGED IN " + mUser.getUid());
Intent intent = new Intent(getApplicationContext(), CustomColorActivity.class);
String uid = mAuth.getCurrentUser().getUid();
String image=mAuth.getCurrentUser().getPhotoUrl().toString();
intent.putExtra("user_id", uid);
if(image!=null || image!=""){
intent.putExtra("profile_picture",image);
}
startActivity(intent);
finish();
Log.d(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
}
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser mUser = firebaseAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
//FaceBook
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
signInWithFacebook(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
}
});
//
}
#Override
protected void onStart() {
super.onStart();
email = (EditText) findViewById(R.id.edit_text_email_id);
password = (EditText) findViewById(R.id.edit_text_password);
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
//FaceBook
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
//
protected void setUpUser() {
user = new User();
user.setEmail(email.getText().toString());
user.setPassword(password.getText().toString());
}
public void onSignUpClicked(View view) {
Intent intent = new Intent(this, SignUpActivity.class);
startActivity(intent);
}
public void onLoginClicked(View view) {
setUpUser();
signIn(email.getText().toString(), password.getText().toString());
}
private void signIn(String email, String password) {
Log.d(TAG, "signIn:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
// 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()) {
Log.w(TAG, "signInWithEmail", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
String uid = mAuth.getCurrentUser().getUid();
intent.putExtra("user_id", uid);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
//
}
private boolean validateForm() {
boolean valid = true;
String userEmail = email.getText().toString();
if (TextUtils.isEmpty(userEmail)) {
email.setError("Required.");
valid = false;
} else {
email.setError(null);
}
String userPassword = password.getText().toString();
if (TextUtils.isEmpty(userPassword)) {
password.setError("Required.");
valid = false;
} else {
password.setError(null);
}
return valid;
}
private void signInWithFacebook(AccessToken token) {
Log.d(TAG, "signInWithFacebook:" + token.getToken());
showProgressDialog();
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// 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()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}else{
String uid=task.getResult().getUser().getUid();
String name=task.getResult().getUser().getDisplayName();
String email=task.getResult().getUser().getEmail();
String image=task.getResult().getUser().getPhotoUrl().toString();
//Create a new User and Save it in Firebase database
User user = new User(uid,name,null,email,name);
user = new User();
// user.setId(authData.getUid());
user.setName(name);
user.setEmail(email);
user.saveUser();
// mRef.child("uid").setValue(uid);
// mRef.child(name).setValue(user);
Log.d(TAG, uid);
Intent intent = new Intent(getApplicationContext(), CustomColorActivity.class);
intent.putExtra("user_id",uid);
intent.putExtra("profile_picture",image);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
MainFragment.java
public class MainFragment extends Fragment {
private static final String TAG = "AndroidBash";
public User user;
private Firebase myFirebaseRef =new Firebase("https://fitmaker-ee2c0.firebaseio.com/");
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private TextView name;
private TextView welcomeText;
private Button changeButton;
private Button revertButton;
private Button FBButton;
private ProgressDialog mProgressDialog;
// To hold Facebook profile picture
private ImageView profilePicture;
public MainFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container,
false);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
//((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
//Add YOUR Firebase Reference URL instead of the following URL
myFirebaseRef = new Firebase("https://fitmaker-ee2c0.firebaseio.com/");
mAuth = FirebaseAuth.getInstance();
name = (TextView) view.findViewById(R.id.text_view_name);
welcomeText = (TextView) view.findViewById(R.id.text_view_welcome);
changeButton = (Button) view.findViewById(R.id.button_change);
revertButton = (Button) view.findViewById(R.id.button_revert);
FBButton = (Button) view.findViewById(R.id.button_fb);
profilePicture = (ImageView) view.findViewById(R.id.profile_picture);
//Get the uid for the currently logged in User from intent data passed to this activity
String uid = getActivity().getIntent().getExtras().getString("user_id");
//Get the imageUrl for the currently logged in User from intent data passed to this activity
String imageUrl = getActivity().getIntent().getExtras().getString("profile_picture");
Log.d(TAG, "MainFrag - OnCreateView Check");
new ImageLoadTask(imageUrl, profilePicture).execute();
//Referring to the name of the User who has logged in currently and adding a valueChangeListener
myFirebaseRef.child(uid).child("name").addValueEventListener(new ValueEventListener() {
//onDataChange is called every time the name of the User changes in your Firebase Database
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Inside onDataChange we can get the data as an Object from the dataSnapshot
//getValue returns an Object. We can specify the type by passing the type expected as a parameter
String data = dataSnapshot.getValue(String.class);
name.setText("Hello " + data + ", ");
}
//onCancelled is called in case of any error
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getActivity().getApplicationContext(), "" + firebaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
//A firebase reference to the welcomeText can be created in following ways :
// You can use this :
//Firebase myAnotherFirebaseRefForWelcomeText=new Firebase("https://androidbashfirebaseupdat-bd094.firebaseio.com/welcomeText");*/
//OR as shown below
myFirebaseRef.child("welcomeText").addValueEventListener(new ValueEventListener() {
//onDataChange is called every time the data changes in your Firebase Database
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Inside onDataChange we can get the data as an Object from the dataSnapshot
//getValue returns an Object. We can specify the type by passing the type expected as a parameter
String data = dataSnapshot.getValue(String.class);
welcomeText.setText(data);
}
//onCancelled is called in case of any error
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getActivity().getApplicationContext(), "" + firebaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
//onClicking changeButton the value of the welcomeText in the Firebase database gets changed
changeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myFirebaseRef.child("welcomeText").setValue("Android App Development # AndroidBash");
}
});
FBButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// log user out
// add choice dialog later
LogOut();
}
});
//onClicking revertButton the value of the welcomeText in the Firebase database gets changed
revertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myFirebaseRef.child("welcomeText").setValue("Welcome to Learning # AndroidBash");
}
});
return view;
}
#Override
public void onResume() {
Log.d(TAG, "onResume of MainFragment");
CheckIfLoggedOut();;
super.onResume();
}
public void CheckIfLoggedOut() {
// here, check if user still logged in.
FirebaseUser mUser = mAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "MainFrag - Signed In (onResume)");
} else {
// User is signed out
Log.d(TAG, "check resume: starting log out for " + mUser.getUid());
LogOut();
}
}
public void LogOut(){
Log.d(TAG, "CHECK #2: USER SIGNED OUT");
getActivity().getIntent().removeExtra("user_id");
getActivity().getIntent().removeExtra("profile_picture");
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
Log.d(TAG, "signed out" + mUser.getUid());
// mAuth.unauth();
Intent intent = new Intent(getActivity().getApplicationContext(),
LoginActivity.class);
myFirebaseRef.unauth();
LoginManager.getInstance().logOut();
startActivity(intent);
Log.d(TAG, "CHECK 3: FINISIHED SIGNED OUT");
Log.d(TAG, "onAuthStateChanged:signed_out");
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(getContext());
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
FirebaseAuth.getInstance().signOut();
Adding this piece of line solved my problem.