I am following the instructions in Firebase in a weekend
When I start the app, I am asked to choose an account. But when I choose the account, the same layer is showing up again and again. Happens on emulator and real device.
In the course it looks like this:
Do you have any tips?
EDIT:
MainActivity.java:
package de.marcofriedmann.testlabor:
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
// Choose an arbitrary request code value
private static final int RC_SIGN_IN = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// initialize Firebase
mFirebaseAuth = FirebaseAuth.getInstance();
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is logged in
String username = firebaseAuth.getCurrentUser().getDisplayName();
TextView welcomeText = (TextView) findViewById(R.id.welcome);
welcomeText.setText(username);
} else {
// User is logged out
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setProviders(Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()))
.build(),
RC_SIGN_IN);
}
}
};
}
#Override
protected void onPause() {
super.onPause();
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
}
Related
I'm using firebase and google sign in. The problem is that when I click on the sign in button, it log in automatically even without any google account registered in firebase auth users! Also the "choose account" dialog doesn't appear when user isn't in firebase auth users and when it is. I would like to show this dialog.
LoginActivity
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.schooltest.MainActivity;
import com.example.schooltest.R;
import com.example.schooltest.ResetPasswordActivity;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.GoogleAuthProvider;
import com.shobhitpuri.custombuttons.GoogleSignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "";
private static final int RC_SIGN_IN = 9001;
private EditText inputEmail, inputPassword;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private View mViewHelper;
GoogleSignInButton button;
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListner;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
//check the current user
if (mAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.et_email_address);
inputPassword = (EditText) findViewById(R.id.et_password);
final Button ahlogin = (Button) findViewById(R.id.login_btn);
progressBar = (ProgressBar) findViewById(R.id.loading_spinner);
TextView btnForgot = findViewById(R.id.forgot);
TextView btnSignUp = (TextView) findViewById(R.id.signup_here_Button);
button = (GoogleSignInButton) findViewById(R.id.login_google_btn);
mViewHelper = findViewById(R.id.view_helper);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
btnForgot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
mAuth = FirebaseAuth.getInstance();
// Checking the email id and password is Empty
ahlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Email is required.", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter Password", Toast.LENGTH_SHORT).show();
return;
}
if(password.length() < 6) {
inputPassword.setError("Password Must be >= 6 Characters");
return;
}
progressBar.setVisibility(View.VISIBLE);
mViewHelper.setVisibility(View.VISIBLE);
ahlogin.setVisibility(View.INVISIBLE);
//authenticate user
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
mViewHelper.setVisibility(View.INVISIBLE);
ahlogin.setVisibility(View.VISIBLE);
if (task.isSuccessful()) {
// there was an error
Log.d(TAG, "signInWithEmail:success");
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
Log.d(TAG, "singInWithEmail:Fail");
Toast.makeText(LoginActivity.this, getString(R.string.failed), Toast.LENGTH_LONG).show();
}
}
});
}
});
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("430102477506-gsgi3mjgd1bie5ml5nf316no2ki3llvj.apps.googleusercontent.com")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Aut Fail", Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
SignUpActivity
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.schooltest.MainActivity;
import com.example.schooltest.R;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.shobhitpuri.custombuttons.GoogleSignInButton;
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "";
private static final int RC_SIGN_IN = 9001;
EditText mName, mEmail,mPassword;
Button mSignupBtn;
FirebaseAuth mAuth;
ProgressBar progressBar;
View mViewHelper;
GoogleSignInButton button;
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListner;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
TextView textView = findViewById(R.id.textView);
textView.setText(Html.fromHtml(getString(R.string.agree_terms)));
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
mEmail = findViewById(R.id.et_email_address);
mPassword = findViewById(R.id.et_password);
mName = findViewById(R.id.et_name);
mSignupBtn = findViewById(R.id.create_btn);
progressBar = findViewById(R.id.loading_spinner);
mViewHelper = findViewById(R.id.view_helper);
button = findViewById(R.id.login_google_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
mAuth = FirebaseAuth.getInstance();
mSignupBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String name = mName.getText().toString().trim();
if(TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(name)) {
mName.setError("Name is required.");
return;
}
if(TextUtils.isEmpty(password)) {
mPassword.setError("Password is required.");
return;
}
if(password.length() < 6) {
mPassword.setError("Password Must be >= 6 Characters");
return;
}
progressBar.setVisibility(View.VISIBLE);
mViewHelper.setVisibility(View.VISIBLE);
mSignupBtn.setVisibility(View.INVISIBLE);
// register the user in firebase
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "User Created", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
else{
Toast.makeText(SignupActivity.this, "Error !" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
mViewHelper.setVisibility(View.INVISIBLE);
mSignupBtn.setVisibility(View.VISIBLE);
}
});
}
});
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("430102477506-gsgi3mjgd1bie5ml5nf316no2ki3llvj.apps.googleusercontent.com")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(SignupActivity.this, "Aut Fail", Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
Main Activity
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import com.example.schooltest.login.LoginActivity;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
private String mName;
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ClassFragment()).commit();
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
// Sets default values only once, first time this is called. The third
// argument is a boolean that indicates whether the default values
// should be set more than once. When false, the system sets the default
// values only the first time it is called.
PreferenceManager.setDefaultValues(this,
R.xml.pref_students, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_information, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_security, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_notifications, false);
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mFirebaseAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
}
}
private void sendToStart() {
Intent startIntent = new Intent(MainActivity.this, FullscreenActivity.class);
startActivity(startIntent);
finish();
}
/**
* Inflates the menu, and adds items to the action bar if it is present.
*
* #param menu Menu to inflate.
* #return Returns true if the menu inflated.
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
/**
* Handles app bar item clicks.
* Don't forget to add intent to addstudent
* #param item Item clicked.
* #return True if one of the defined items was clicked.
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_addStudent:
displayToast(getString(R.string.action_addStudent_message));
return true;
case R.id.action_settings:
Intent settingsIntent = new Intent(this,
SettingsActivity.class);
startActivity(settingsIntent);
return true;
case R.id.menu_logout_btn:
FirebaseAuth.getInstance().signOut();
sendToStart();
return true;
default:
// Do nothing
}
return super.onOptionsItemSelected(item);
}
/**
* Displays a Toast with the message.
*
* #param message Message to display
*/
public void displayToast(String message) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT).show();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_class:
selectedFragment = new ClassFragment();
break;
case R.id.navigation_due:
selectedFragment = new DueFragment();
break;
case R.id.navigation_messages:
selectedFragment = new MessagesFragment();
break;
case R.id.navigation_class_updates:
selectedFragment = new ClassUpdatesFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
}
I am making a simple chat app with firebase sign in. Everything works great but one thing that bothers me is if a user is logged in, after starting the app it shows the login activity for a while before redirecting to the second second every time and it doesn't look good. Below are the screenshot for better understanding
This is the activity that is shown every time after the app is opened for 1-2 second even if the user is logged in
This is the logged in page
What I want is if a user is logged in and opens the app he should see the second activity directly
MainActivity (Login activity)
package com.example.fireapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends AppCompatActivity {
private EditText emailEditText;
private EditText passwordEditText;
private Button loginButton;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListner;
private Button signInButton;
private SignInButton googleButton;
private GoogleSignInClient mGoogleSignInClient;
private int RC_SIGN_IN = 1;
private String TAG = "Info";
private ProgressBar progressBar;
int flag = 0;
DatabaseReference reference;
//firebase
FirebaseUser user;
String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emailEditText = findViewById(R.id.emailEditText);
passwordEditText = findViewById(R.id.passwordEditText);
loginButton = findViewById(R.id.signUpButton);
signInButton = findViewById(R.id.signInButton);
googleButton = findViewById(R.id.googleButton);
progressBar = findViewById(R.id.progressBar);
mAuth = FirebaseAuth.getInstance();
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null && flag != 1) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
finish();
}
}
};
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
login();
}
});
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.GONE);
startActivity(new Intent(MainActivity.this, accountActivity.class));
// finish();
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
googleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 1;
signIn();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
private void login() {
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
progressBar.setVisibility(View.GONE);
Toast.makeText(this, "Fields are Empty", Toast.LENGTH_SHORT).show();
} else {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "Sign in unsuccessful!!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
user = mAuth.getCurrentUser();
userId = user.getUid();
reference = FirebaseDatabase.getInstance().getReference("User").child(userId);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
Toast.makeText(MainActivity.this, "Google Sign in Successful", Toast.LENGTH_SHORT).show();
finish();
} else {
startActivity(new Intent(MainActivity.this, DetailsActivity.class));
Toast.makeText(MainActivity.this, "Google Sign in Successful", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
}
}
});
}
}
Main2Activity
package com.example.fireapp;
import android.content.Intent;
import android.os.Bundle;
import com.bumptech.glide.Glide;
import com.example.fireapp.model.Users;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class Main2Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private View headerView;
private TextView usernameText;
private TextView emailText;
private CircleImageView userImage;
private FirebaseUser firebaseUser;
private DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("fireApp");
//navigation drawer
drawerLayout = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
//user details inside navigation drawer
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
headerView = navigationView.getHeaderView(0);
usernameText = headerView.findViewById(R.id.usernameText);
userImage = headerView.findViewById(R.id.userImage);
emailText = headerView.findViewById(R.id.userEmail);
setUserDetails();
if(savedInstanceState==null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new chatFragment()).commit();
navigationView.setCheckedItem(R.id.nav_chat);
}
}
private void setUserDetails() {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("User").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Users user= dataSnapshot.getValue(Users.class);
try {
usernameText.setText(user.getUsername());
emailText.setText(firebaseUser.getEmail());
if (user.getImageUrl().equals("default")) {
userImage.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(getApplicationContext()).load(user.getImageUrl()).into(userImage);
}
}
catch (Exception e){
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch(menuItem.getItemId()){
case R.id.nav_chat:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new chatFragment()).commit();
break;
case R.id.nav_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new profileFragment()).commit();
break;
case R.id.nav_feed:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new feedFragment()).commit();
break;
case R.id.nav_share:
Toast.makeText(this, "Share!", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_feedback:
Toast.makeText(this, "Feedback!", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//3 dots menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.logout) {
AuthUI.getInstance()
.signOut(Main2Activity.this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(Main2Activity.this, MainActivity.class));
finish();
}
});
return true;
} else
return false;
}
}
Please help
A simple solution to save you from that is to create a SharedPreferences
Assuming you created a preference for isLoggedIn then, inside your first activity that opens, the very first thing you do in onCreate is to check whether the user isLoggedIn. Then from there you can do if..else intent MainActivity or LoginActivity.
Try to finish the activity once the user login
finish();
Then take back the user to the LoginActivity when he logs out
Rather then assigning listener you can do it like this
if(mFirebaseAuth.getCurrentUser() == null)
startActivity(new Intent(LaunchScreen.this, LoginScreen.class));
else
startActivity(new Intent(LaunchScreen.this, MainActivity.class));
finish();
try this
The process that takes a login from an external service is not immediate, I recommend using an async task, so that while the login process is done, the above does not happen to you
public class MainActivity extends AppCompatActivity {
ProgressDialog dialog;
....
....
#Override
protected void onCreate(Bundle savedInstanceState) {
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new loginTask().execute(true);
}
});
}
}
class loginTask extends AsyncTask<Boolean, Void, String> {
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MainActivity.this, "", "Loading", true);
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
dialog.dismiss();
/** Redirect to main2 class **/
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
super.onPostExecute(s);
}
#Override
protected String doInBackground(Boolean... booleans) {
/** Your code **/
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
progressBar.setVisibility(View.GONE);
Toast.makeText(this, "Fields are Empty",Toast.LENGTH_SHORT).show();
} else {
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "Sign in unsuccessful!!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
Try using finish() after the intent, this activity will be closed and therefore, will become also unreachable.
I i am working with firebase realtime database.. I retrieved data and everything but my main problem is that the data is not being displayed unless i press back button.. I went through stacks everywhere it suggested to notifyDataSetChanged(); which i did before, but still no luck. As i am using GridLayout i cant use the adapter in the addListeneOnDatachange function as it shows error saying that it is not allowed to add the adapter there for my RecyclerViewAdapter.
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class HomeActivity extends AppCompatActivity {
String userID;
List<CourseModel> listCourse;
TextView btnSignOut, UserName;
/*---- Firebase Database stuff ----*/
FirebaseAuth mAuth;
FirebaseUser user;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference myRef;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
/*-------Finding View---------*/
btnSignOut = (TextView) findViewById(R.id.btnsignout_home);
UserName = findViewById(R.id.username);
RecyclerView myrv = findViewById(R.id.recyclerviewcourse);
myrv.setLayoutManager(new GridLayoutManager(this,2));
// CourseCode();
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
startActivity(new Intent(HomeActivity.this, SignInActivity.class));
}
}
};
/* ----------------- Firebase Elements -----------------*/
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
userID = user.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
myRef = rootRef.child("Users");
/*------------------------------------------------------------------*/
listCourse = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child(userID).child("userName").getValue(String.class);
UserName.setText(userName);
String coursecode[] = new String[10];
String coursename[] = new String[10];
listCourse.clear();
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Hello", "Failed to read value.", error.toException());
}
});
RecyclerViewAdapterCourse myAdapter = new RecyclerViewAdapterCourse(this,listCourse);
myAdapter.notifyDataSetChanged();
myrv.setAdapter(myAdapter);
}
}
You need to call myAdapter.notifyDataSetChanged() every time the data changes. In your case this means you need to call it at the end of the onDataChanged(DataSnapShot dataSnapShot) function.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child(userID).child("userName").getValue(String.class);
UserName.setText(userName);
String coursecode[] = new String[10];
String coursename[] = new String[10];
listCourse.clear();
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
myAdapter.notifyDataSetChanged()
}
I'm using Android Studio and I want to use Google API as a login. If the login is succesful, it can change to another activity. Besides that, I want to show the account name and profile picture in another activity, but I got this error:
error: identifier expected GoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this,this).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
My code:
package com.example.alif.angkotcoba;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener,GoogleApiClient.OnConnectionFailedListener {
private SignInButton SignIn;
private GoogleApiClient GoogleApiClient;
private static final int RC_SIGN_IN =9001;
private static final String TAG ="signInActivity";
GoogleSignInOptions gso=new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
GoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this,this).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SignIn = (SignInButton) findViewById(R.id.btngoogle);
SignIn.setOnClickListener(this);
}
public void gotoSecondActivity (View view) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btngoogle:
signIn ();
break;
}
}
public void signIn ()
{
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(GoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
public void handleResult (GoogleSignInResult result) {
GoogleSignInAccount account = result.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String img_url = account.getPhotoUrl().toString();
}
#Override
public void onActivityResult(int requestcode,int resultcode,Intent data) {
super.onActivityResult(requestcode,resultcode,data);
if (requestcode==RC_SIGN_IN){
GoogleSignInResult result=Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG,"handleSignInResult:"+ result.isSuccess());
if (result.isSuccess()){
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG,"onConnectionFailed:"+connectionResult);
}
}
You need a variable name in the declaration. The problem is that you are trying to declare a variable with the same name as a class:
private GoogleApiClient GoogleApiClient;
That won't work. As far as the compiler is concerned, all you have on the left side of the assignment is the type name GoogleApiClient. Try something like this:
private GoogleApiClient googleApiClient; // note change of case!
googleApiClient = ...
Also, you are probably better off initializing anything that depends on this inside onCreate rather than when the variable is declared.
I am new to android studio and Firebase. After watching some online tutorials I wrote the code for a login page. Can anyone please debug it for me?
Please note that my login button is an image view
The name of the app is Riddler
package in.mihiljose.riddler;
import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginSignUp extends AppCompatActivity {
private EditText mEmailField;
private EditText mPasswordField;
private ImageView mLoginBtn;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_sign_up);
mEmailField = (EditText)findViewById(R.id.emailField);
mPasswordField = (EditText)findViewById(R.id.passwordField);
mLoginBtn = (Button) findViewById(R.id.loginBtn);
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser()!=null){
startActivity(new LoginSignUp().this,MainActivity.class);
}
}
};
}
mLoginBtn.setOnClickListener(new View.OnClickListener()) {
#Override
public void onClick(View view) {
startSignIn();
}
});
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
}
private void startSignIn(){
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
if (TextUtils.isEmpty(email)||TextUtils.isEmpty(password)){
Toast.makeText(LoginSignUp.this,"Empty Fields !!",Toast.LENGTH_LONG).show();
}else {
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(LoginSignUp.this,"Sign in Problem",Toast.LENGTH_LONG).show();
}
}
})
}
}
Find this sample code for Login Activity: (Ensure you have done signIn using "createUserWithEmailAndPassword" before doing login)
public class LoginActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener authStateListener;
private ProgressBar progressBar;
private Button btnSignup, btnLogin, btnReset;
private SignInButton btn_google_login;
private LoginButton btn_facebook_login;
private static final int RC_SIGN_IN = 9001;
private AuthCredential mCredential;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
// set the view now
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d("LoginActivity", "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d("LoginActivity", "onAuthStateChanged:signed_out");
}
}
};
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// 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.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
mCredential = EmailAuthProvider.getCredential(email, password);
finish();
}
}
});
}
});
}
#Override
public void onStart() {
super.onStart();
auth.addAuthStateListener(authStateListener);
}
#Override
public void onStop() {
super.onStop();
if (authStateListener != null) {
auth.removeAuthStateListener(authStateListener);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private void SignOut() {
//Firebase sign out
if (auth.getCurrentUser() != null) {
auth.signOut();
Log.i("LoginActivity","Firebase logout successfully");
}
//Facebook SignOut
LoginManager.getInstance().logOut();
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.i("LoginActivity","onDestroy");
SignOut();
}
}
If you are reading data from Firebase's real time database, the default read database permission is set to false. You can modify it to true from the database's permission tab.