Main activity opens every time on app startup - android

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.

Related

Unable to select different account on google Sign In

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;
}
};
}

Attempt to invoke virtual method 'void com.google.android.gms.common.SignInButton.setSize(int)' on a null object reference

package design.nxn.login_template_01;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
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.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.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.text.BreakIterator;
import java.util.Objects;
import design.nxn.login_template_01.Tools.CustomViewPager;
import design.nxn.login_template_01.Tools.ViewPagerAdapter;
public class LoginActivity extends BaseActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {
private static final String TAG = BaseActivity.class.getSimpleName();
private static final int RC_SIGN_IN = 420;
private GoogleApiClient mGoogleApiClient;
private ProgressDialog mProgressDialog;
private SignInButton btnSignIn;
private GoogleSignInClient mGoogleSignInClient;
private String personPhotoUrl;
GoogleSignInOptions gso;
BreakIterator mStatusTextView;
private static final int LOGIN_FRAGMENT = 0;
private static final int SIGNUP_FRAGMENT = 1;
private static final int RESET_PASSWORD_FRAGMENT = 2;
private Fragment newFragment;
private CustomViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnSignIn = (SignInButton)findViewById(R.id.sign_in_button);
initializeGPlusSettings();
initializeControls();
findViewById(R.id.sign_in_button).setOnClickListener(this);
viewPager = findViewById(R.id.viewpager);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(viewPagerAdapter);
viewPager.setPagingEnabled(false);
changeFragment(LOGIN_FRAGMENT);
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void initializeControls() {
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
}
public void onStart() {
super.onStart();
GoogleSignInAccount account =
GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task =
GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleGPlusSignInResult(GoogleSignInResult result) {
Log.d(TAG,"handleSignInResult:" +result.isSuccess());
if (result.isSuccess()){
GoogleSignInAccount acct = result.getSignInAccount();
String personname = acct.getDisplayName();
personPhotoUrl = Objects.requireNonNull(acct.getPhotoUrl()).toString();
String personEmail = acct.getEmail();
Intent intent = new Intent(LoginActivity.this,SecondActivity.class);
intent.putExtra("personname",personname);
intent.putExtra("email",personEmail);
intent.putExtra("personphotoUrl",personPhotoUrl);
startActivity(intent);
finish();
}
}
private void handleSignInResult(Task<GoogleSignInAccount> task) {
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
// Signed in successfully, show authenticated UI.
updateUI(account);
}
catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
updateUI(null);
}
}
private void initializeGPlusSettings() {
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this,this).addApi(Auth.GOOGLE_SIGN_IN_API,gso).build();
btnSignIn.setSize(SignInButton.SIZE_STANDARD);
}
private void changeFragment(int fragmentType) {
switch (fragmentType) {
case LOGIN_FRAGMENT:
viewPager.setCurrentItem(LOGIN_FRAGMENT);
break;
case SIGNUP_FRAGMENT:
viewPager.setCurrentItem(SIGNUP_FRAGMENT);
break;
case RESET_PASSWORD_FRAGMENT:
viewPager.setCurrentItem(RESET_PASSWORD_FRAGMENT);
break;
default:
viewPager.setCurrentItem(LOGIN_FRAGMENT);
break;
}
}
public void signUpClick(View view) {
changeFragment(SIGNUP_FRAGMENT);
}
public void signInClick(View view) {
changeFragment(LOGIN_FRAGMENT);
}
public void resetPasswordClick(View view) {
changeFragment(RESET_PASSWORD_FRAGMENT);
}
public void backClick(View view){
changeFragment(LOGIN_FRAGMENT);
}
#Override
public void onBackPressed() {
if (viewPager.getCurrentItem() == LOGIN_FRAGMENT)
super.onBackPressed();
else {
changeFragment(LOGIN_FRAGMENT);
}
}
public void logInButtonClicked() {
Toast.makeText(this, R.string.login_button_click, Toast.LENGTH_SHORT).show();
}
public void signUpButtonClicked() {
Toast.makeText(this, R.string.signup_button_click, Toast.LENGTH_SHORT).show();
}
public void resetPasswordButtonClicked() {
Toast.makeText(this, R.string.reset_password_button_clicked, Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.sign_in_button:
signIn();
case R.id.logout:
signOut();
break;
}
}
private void signOut() {
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// ...
}
});
}
private void revokeAccess() {
mGoogleSignInClient.revokeAccess()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// ...
}
});
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void updateUI(GoogleSignInAccount account) {
if (account != null) {
mStatusTextView.setText(getString(R.string.signed_in_fmt, account.getDisplayName()));
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.logout).setVisibility(View.VISIBLE);
}
else {
mStatusTextView.setText(String.valueOf(R.string.signed_out));
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.logout).setVisibility(View.GONE);
}
}
}
You are setting click here
switch (view.getId()) {
case R.id.sign_in_button:
signIn();
As per this code you need to use
btnSignIn.setOnClickListener(this);
Instead of
findViewById(R.id.sign_in_button).setOnClickListener(this);

How to control activity in Android while its looged in and logged out?

I am trying to make an android app for blood bank in android using Firebase. My home page is showing a list of donner with there city and contact no. but the problem is when user is logged in and then going back to the home page where he/she can see the list of donner the app stops.
For better understanding I'm giving my whole class code here. Can anyone please help me in this process? Thanks in advance.
package alik.com.pmscs;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import alik.com.loader.Information;
public class HomePage extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Intent intent;
FirebaseAuth auth;
FirebaseAuth.AuthStateListener authStateListener;
ListView listView;
ArrayList <Information> informations;
Firebase firebase;
ImageView call;
//FirebaseUser user;
FirebaseAuth.AuthStateListener listener;
GoogleSignInOptions signInOptions;
DatabaseReference reference;
NavigationView navigationView;
com.firebase.ui.database.FirebaseListAdapter <Information> adapter;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
auth=FirebaseAuth.getInstance();
listener=new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
FirebaseUser user=auth.getCurrentUser();
if(user==null){
Menu menu=navigationView.getMenu();
menu.findItem(R.id.nav_signoutfrom).setVisible(false);
menu.findItem(R.id.nav_profileon).setVisible(false);
menu.findItem(R.id.nav_adddonnor).setVisible(false);
}
}
};
listView=(ListView)findViewById(R.id.listView);
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
final FirebaseDatabase database=FirebaseDatabase.getInstance();
reference=database.getReference();
reference.keepSynced(true);
adapter=new FirebaseListAdapter<Information>(
this,
Information.class,
R.layout.donorlist,
reference
) {
#Override
protected void populateView(View v, Information model, int position) {
((TextView)v.findViewById(R.id.donnor_blood)).setText(model.getBloodgroup());
((TextView)v.findViewById(R.id.donor_name)).setText(model.getName());
((TextView)v.findViewById(R.id.donor_contact)).setText(model.getContact());
((TextView)v.findViewById(R.id.donor_city)).setText(model.getCity()+", "+model.getCountry());
}
};
listView.setAdapter(adapter);
ColorDrawable colorDrawable=new ColorDrawable(Color.parseColor("#bc212b"));
getSupportActionBar().setBackgroundDrawable(colorDrawable);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_reg) {
// Handle the camera action
intent=new Intent(getApplicationContext(),RegisterAccount.class);
startActivity(intent);
//finish();
} else if (id == R.id.nav_login) {
intent=new Intent(getApplicationContext(),Login.class);
startActivity(intent);
//finish();
}
else if (id == R.id.nav_profileon) {
if(listener!=null){
Toast.makeText(getApplicationContext(),"This Feature is Comming Soon!!", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(),"Please Login First", Toast.LENGTH_LONG).show();
}
}
else if(id==R.id.nav_adddonnor){
if(listener!=null){
startActivity(new Intent(getApplicationContext(),DonnarRegistration.class));
//finish();
}
else{
Toast.makeText(getApplicationContext(),"Please Login First", Toast.LENGTH_LONG).show();
}
}
else if (id == R.id.nav_signoutfrom) {
if(listener!=null){
FirebaseAuth.getInstance().signOut();
Toast.makeText(getApplicationContext(), "Sign Out Successfully", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Please Login First", Toast.LENGTH_LONG).show();
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
protected void onStop() {
super.onStop();
if(listener!=null){
auth.removeAuthStateListener(listener);
}
}
#Override
protected void onStart() {
super.onStart();
auth.addAuthStateListener(listener);
}
#Override
protected void onPostResume() {
super.onPostResume();
}
}
My Login Class code is here
package alik.com.pmscs;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
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.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class Login extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ColorDrawable colorDrawable=new ColorDrawable(Color.parseColor("#bc212b"));
getSupportActionBar().setBackgroundDrawable(colorDrawable);
getSupportActionBar().setTitle("Sign Up");
auth = FirebaseAuth.getInstance();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
auth=FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(), RegisterAccount.class);
startActivity(intent);
finish();
}
});
btnLogin.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(), "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);
auth.signInWithEmailAndPassword(email, password).addOnCompleteListener(Login.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
Toast.makeText(getApplicationContext(),"There is an error",Toast.LENGTH_LONG).show();
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(Login.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(Login.this, HomePage.class);
startActivity(intent);
finish();
}
}
});
}
});
}
}
So the problem is when I am logged in then trying to go back to my Homepage activity it stopped. So I need help from experts to solve it. It'll be a pleasure if you help me in this task.
My gradle file:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.firebase:firebase-client-android:2.4.0'
compile 'com.google.firebase:firebase-auth:10.0.1'
compile 'com.google.firebase:firebase-core:10.0.1'
compile 'com.google.firebase:firebase-database:10.0.1'
compile 'com.google.firebase:firebase-storage:10.0.1'
compile 'com.firebaseui:firebase-ui-database:0.4.0'
}
apply plugin: 'com.google.gms.google-services'
Did you try to change your Login activity as follows? Here, I'm checking if the user is already logged in in the Login activity, and if it is I'm calling the HomePage activity.
public class Login extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
Intent intent = new Intent(Login.this, HomePage.class);
startActivity(intent);
finish();
}
setContentView(R.layout.activity_login);
ColorDrawable colorDrawable=new ColorDrawable(Color.parseColor("#bc212b"));
getSupportActionBar().setBackgroundDrawable(colorDrawable);
getSupportActionBar().setTitle("Sign Up");
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(), RegisterAccount.class);
startActivity(intent);
finish();
}
});
btnLogin.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(), "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);
auth.signInWithEmailAndPassword(email, password).addOnCompleteListener(Login.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
Toast.makeText(getApplicationContext(),"There is an error",Toast.LENGTH_LONG).show();
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(Login.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(Login.this, HomePage.class);
startActivity(intent);
finish();
}
}
});
}
});
}
Hope this can match your requirements

Firebase Authentication Error

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.

Sign in with google and facebook not stable

Im using google and facebook firebase Authentication in my app but it's not stable, sometimes it's work but other times it doesn't, i don't know what is wrong with my code to make it not stable.
here is my code:
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.hima.sftani.R;
import com.example.hima.sftani.callback.CarAvailabilityListener;
import com.example.hima.sftani.database.FirebaseHandler;
import com.example.hima.sftani.util.Connection;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
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;
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.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.GoogleAuthProvider;
import butterknife.Bind;
import butterknife.BindDrawable;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
#Bind(R.id.email_login) EditText email;
#Bind(R.id.password_login) EditText password;
#Bind(R.id.main_activity_progress_bar) ProgressBar progressBar;
#Bind(R.id.link_signup) TextView signupLink;
#BindDrawable(R.drawable.ic_error_24dp) Drawable errorIcon;
#Bind(R.id.googlebtn) SignInButton mGoogleBtn;
private String mEmail,mPassword;
private static final int RC_SIGN_IN = 1;
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
private ProgressDialog mProgressDialog;
private LoginButton loginButton;
private CallbackManager mCallbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mProgressDialog = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
mProgressDialog.setMessage("Please Wait");
if (FirebaseAuth.getInstance().getCurrentUser()!=null){
mProgressDialog.show();
FirebaseHandler.checkEmailAvailability(FirebaseAuth.getInstance().getCurrentUser().getEmail(), new CarAvailabilityListener() {
#Override
public void onSearchCompleted(boolean isFounded) {
if(isFounded){
startActivity(new Intent(MainActivity.this, NavigationDrawerActivity.class));
MainActivity.this.finish();
mProgressDialog.dismiss();
}
else{
startActivity(new Intent(MainActivity.this, CompleteProfile.class));
MainActivity.this.finish();
mProgressDialog.dismiss();
}
}
});
}
errorIcon.setBounds(new Rect(0, 0, errorIcon.getIntrinsicWidth(), errorIcon.getIntrinsicHeight()));
mCallbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("Login", "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d("Login", "facebook:onCancel");
// ...
}
#Override
public void onError(FacebookException error) {
Log.d("Login", "facebook:onError", error);
// ...
}
});
signupLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SignUpActivity.class));
}
});
// ======= GOOGLE SIGN IN ==========
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API,gso).build();
mGoogleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
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) {
Log.d("TAG", "signInWithCredential:onComplete:" + task.isSuccessful());
String emailNode =task.getResult().getUser().getEmail();
Log.v("URI",emailNode);
// 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(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
FirebaseHandler.checkEmailAvailability(emailNode, new CarAvailabilityListener() {
#Override
public void onSearchCompleted(boolean isFounded) {
if(isFounded){
startActivity(new Intent(MainActivity.this, NavigationDrawerActivity.class));
MainActivity.this.finish();
mProgressDialog.dismiss();
}
else{
startActivity(new Intent(MainActivity.this, CompleteProfile.class));
MainActivity.this.finish();
mProgressDialog.dismiss();
}
}
});
}
});
}
private void handleFacebookAccessToken(AccessToken token) {
Log.d("Login", "handleFacebookAccessToken:" + token);
mProgressDialog.show();
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("Login", "signInWithCredential:onComplete:" + task.isSuccessful());
String emailNode =task.getResult().getUser().getEmail();
// 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("Login", "signInWithCredential", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
FirebaseHandler.checkEmailAvailability(emailNode, new CarAvailabilityListener() {
#Override
public void onSearchCompleted(boolean isFounded) {
if(isFounded){
startActivity(new Intent(MainActivity.this, NavigationDrawerActivity.class));
MainActivity.this.finish();
mProgressDialog.dismiss();
}
else{
startActivity(new Intent(MainActivity.this, CompleteProfile.class));
MainActivity.this.finish();
mProgressDialog.dismiss();
}
}
});
}
});
}
#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) {
mProgressDialog.show();
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed, update UI appropriately
// ...
mProgressDialog.dismiss();
}
}
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
public void login(View view) {
if (!Connection.isNetworkAvailable(this)){
Toast.makeText(this, "Check your internet connection!", Toast.LENGTH_SHORT).show();
}
else if (!isDataValid()){
Toast.makeText(this, "All Fields required", Toast.LENGTH_SHORT).show();
}
else
login();
}
private void login() {
progressBar.setVisibility(View.VISIBLE);
FirebaseAuth.getInstance().signInWithEmailAndPassword(mEmail,mPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
progressBar.setVisibility(View.INVISIBLE);
startActivity(new Intent(MainActivity.this,NavigationDrawerActivity.class));
MainActivity.this.finish();
}
else {
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
}
}
});
}
private boolean isDataValid() {
mEmail = email.getText().toString().trim();
mPassword =password.getText().toString();
if(mEmail.equals(""))
email.setError("Required",errorIcon);
if(mPassword.equals(""))
password.setError("Required",errorIcon);
return !(mEmail.equals("")||mPassword.equals(""));
}
}

Categories

Resources