In my loginactivity, I have an google Sign In button to LogIn.
I checked and works fine.
I had anothers buttons to log out and Revoke and worked fine too.
This is my code of the loggin screen.
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
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.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
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.common.api.OptionalPendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener
{
private static final String TAG = MainActivity.class.getSimpleName();
private static final int RC_SIGN_IN = 007;
private GoogleApiClient mGoogleApiClient;
private ProgressDialog mProgressDialog;
private SignInButton btnSignIn;
List<String> profile=new ArrayList<>();
private MyGoogleApi_Singleton myGoogleApi_singleton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSignIn = (SignInButton) findViewById(R.id.sign_in_button);
btnSignIn.setOnClickListener(this);
updateUI(false);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
/* Customizing G+ button
btnSignIn.setSize(SignInButton.SIZE_STANDARD);
btnSignIn.setScopes(gso.getScopeArray());*/
//Create a new objet to handle in all class
myGoogleApi_singleton= new MyGoogleApi_Singleton();
myGoogleApi_singleton.getInstance(mGoogleApiClient);
}
private void signIn()
{
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void signOut()
{
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>()
{
#Override
public void onResult(Status status)
{
updateUI(false);
}
});
}
private void revokeAccess()
{
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>()
{
#Override
public void onResult(Status status)
{
updateUI(false);
}
});
}
private void handleSignInResult(GoogleSignInResult result)
{
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess())
{
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personPhotoUrl = acct.getPhotoUrl().toString();
String email = acct.getEmail();
String idnumber= acct.getId();
Log.e(TAG, "Name: " + personName + ", email: " + email
+ ", Image: " + personPhotoUrl+ ", Id Number: "+ idnumber);
//Save the data into the arraylist
profile.add(idnumber);
profile.add(personName);
profile.add(email);
profile.add(personPhotoUrl);
//save into sharedpreferences
StringBuilder stringBuilder = new StringBuilder();
for (String s:profile)
{
stringBuilder.append(s);
stringBuilder.append(",");
}
SharedPreferences sharpref = getSharedPreferences("ProfileList",0);
SharedPreferences.Editor editor = sharpref.edit();
editor.putString("ProfileList", stringBuilder.toString());
editor.commit();
goIndexScreen();
} else
{
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.sign_in_button:
signIn();
break;
default:
break;
}
}
#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)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
#Override
public void onStart()
{
super.onStart();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone())
{
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d(TAG, "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else
{
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
showProgressDialog();
opr.setResultCallback(new ResultCallback<GoogleSignInResult>()
{
#Override
public void onResult(GoogleSignInResult googleSignInResult)
{
hideProgressDialog();
handleSignInResult(googleSignInResult);
}
});
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
}
//method to show a progress dialog during the SignIn
private void showProgressDialog()
{
if (mProgressDialog == null)
{
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
//method to hide the progress dialog
private void hideProgressDialog()
{
if (mProgressDialog != null && mProgressDialog.isShowing())
{
mProgressDialog.hide();
}
}
//method to show or hide the buttons
private void updateUI(boolean isSignedIn)
{
if (isSignedIn)
{
btnSignIn.setVisibility(View.GONE);
} else
{
btnSignIn.setVisibility(View.VISIBLE);
}
}
//method to go to next activity
private void goIndexScreen()
{
Intent intent=new Intent(this,Index.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
When the login is succes, the app jump to another activity.
I need to LogOut from this activity, but I need to a mGoogleApiClient from LoginActivity and I donĀ“t know how I could doing.
I have create a new class (singleton) here my code
import com.google.android.gms.common.api.GoogleApiClient;
class MyGoogleApi_Singleton {
private static final String TAG = "GoogleApiClient";
private static MyGoogleApi_Singleton instance = null;
private static GoogleApiClient mGoogleApiClient = null;
private MyGoogleApi_Singleton(Context context) {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(context)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
public static MyGoogleApi_Singleton getInstance(Context context) {
if(instance == null) {
instance = new MyGoogleApi_Singleton(context);
}
return instance;
}
//methods SingIn,SignOut and Revoke
public void Login(GoogleApiClient bGoogleApiClient){
}
public void Logout(){
if(mGoogleApiClient.isConnected()) {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
Log.d("LOGOUT-RESULT","LOGOUT");
}
});
}
}
public void Revoke() {
if ((mGoogleApiClient.isConnected())) {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
Log.d("REVOKE-RESULT","REVOKE");
}
});
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
This is the code of Index activity
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
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.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.util.ArrayList;
import java.util.List;
public class Index extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ImageView ivprofile;
private TextView tvname;
private TextView tvemail;
private TextView tvidnumber;
private String picprofile;
private String name;
private String idnumber;
private String email;
final List<String> profile = new ArrayList<String>();
private View headerview;
private GoogleApiClient mGoogleApiClient;
private MyGoogleApi_Singleton myGoogleApiSingleton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//create a headerview to conect to header of left menu
headerview=navigationView.getHeaderView(0);
ivprofile=(ImageView)headerview.findViewById(R.id.imageProfile);
tvname=(TextView)headerview.findViewById(R.id.fullName);
tvemail=(TextView)headerview.findViewById(R.id.email);
tvidnumber=(TextView) headerview.findViewById(R.id.idNumber);
//Load file saved by sharedpreferences into a new arraylist
final SharedPreferences sharpref = getSharedPreferences("ProfileList",0);
String Items = sharpref.getString("ProfileList","");
String [] listItems = Items.split(",");
for (int i=0;i<listItems.length;i++){
profile.add(listItems[i]);
}
//get the profile
idnumber=profile.get(0);
name=profile.get(1);
email=profile.get(2);
picprofile=profile.get(3);
Log.d("ArrayPerfil", name+email+idnumber+picprofile);
tvname.setText(name);
tvidnumber.setText(idnumber);
tvemail.setText(email);
Glide.with(this).load(picprofile).into(ivprofile);
//get the mgoogleapiclient objet
myGoogleApiSingleton=new MyGoogleApi_Singleton();
mGoogleApiClient=myGoogleApiSingleton.get_GoogleApiClient();
#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.index, 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_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}else if (id == R.id.logout) {
myGoogleApiSingleton.getInstance(context).Logout();
goLoginScreen();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//method to go to login screen
private void goLoginScreen() {
Intent intent=new Intent(this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
As you told me, I created a Transparent Activity. I added the method handleSignInResult because is calling on the method OnActivityResult.
This is the code:
public class GoogleActivity extends AppCompatActivity {
public static final int RC_SIGN_IN = 1000;
private static final String ACTION = "calling_action";
public static Intent getIntent(Context context, int action, Intent actionIntent) {
Intent i = new Intent(context, GoogleActivity.class);
i.putExtra(ACTION, action);
i.putExtra(Intent.EXTRA_INTENT, actionIntent);
return i;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Intent actionIntent;
int action = getIntent().getIntExtra(ACTION, 0);
switch (action) {
case RC_SIGN_IN:
actionIntent = (Intent) getIntent().getExtras().get(Intent.EXTRA_INTENT);
if (actionIntent != null)
startActivityForResult(actionIntent, RC_SIGN_IN);
break;
case 0:
default:
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RC_SIGN_IN:
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
finish();
return;
}
}
private void handleSignInResult(GoogleSignInResult result)
{
if (result.isSuccess())
{
// Signed in successfully
Log.d("SIGNIN", "YOU ARE LOG IN");
} else
{
// Signed out,
Log.d("SIGNIN", "YOU ARE NOT LOG IN");
}
}
}
I wait for your help!
Thanks!
This is not a bad idea, in fact it is you should do. If you want to handle all actions and events from Google Auth, the easiest, elegant, reusable, and testeable way to do it is to wrap this logic in one or more clases dedicated to that.
If you have few actions you could encalsupate all of them in only one wrap class. For example you could create a class GoogleSingInWrapper and use the Singleton patter to make sure there is only one instance in your entire app.
public class GoogleSingInWrapper {
private static GoogleSingInWrapper instance;
private GoogleApiClient mGoogleApiClient;
private GoogleSingainWrapper() {
// Private constructor to deny the creation of this object through the constructor and prevent creating more then one instance
mGoogleApiClient = /*create your client here*/;
}
public static getInstance(/*params you need*/) {
if(instance == null)
instance = new GoogleSingInWrapper (/*params*/);
return instance;
}
public void login(/*params*/) {
// Login
}
// Other methods
}
So to get (and create an instance if doesn't exists yet) an instance of GoogleSingInWrapper you use:
GoogleSingInWrapper.gerInstance(/*params*/);
Now if you put all variables and logic in this class you can access them from where you want. The mGoogleApiClient must be in this wrapper.
You can now add all method you need such login, logout and revoke.
And use it as follows:
GoogleSingInWrapper.getInstance().login(/*params*/);
GoogleSingInWrapper.getInstance().logout(/*params*/);
GoogleSingInWrapper.getInstance().revoke(/*params*/);
You shouldn't use mGoogleApiClient directly, it should be encapsulated in GoogleSingInWrapper.
EDIT
When I say mGoogleApiClient should be private inside GoogleSingInWrapper it means that you should't have access to it outside the GoogleSingInWrapper class. If you create a GoogleSingInWrapper but you create a method called
public GoogleApiClient get_GoogleApiClient();
you problems keep existing, because you are still using this mGoogleApiClientin all activities. You don't want this, so you want to be decoupled of this object in all activities.
Following your edits, I'll type here more code, but the more free code I give you less you learn.
public class GoogleSingInWrapper {
private static GoogleSingInWrapper instance;
private GoogleApiClient mGoogleApiClient;
private GoogleSingainWrapper(Context context) {
// Private constructor to deny the creation of this object through the constructor and prevent creating more then one instance
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(context)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
public static getInstance(Context context) {
if(instance == null)
instance = new GoogleSingInWrapper (/*params*/);
return instance;
}
public void login(/*params*/) {
// Login
}
// Other methods
public void logout(){
if(mGoogleApiClient.isConnected()) {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
Log.d("LOGOUT-RESULT","LOGOUT");
}
});
}
}
}
This should look like your GoogleSingInWrapper. And to call for example logout method, you should call as follows:
if (id == R.id.logout) {
GoogleSingInWrapper.getInstance(context).logout();
goLoginScreen();
}
Note the constructor is Private intentionally because you doesn't want to call new GoogleSingInWrapper. If you do that, you are creating multiple instances of this object ant you're breaking the Singleton pattern.
Also, you may note that some processes like login, needs an Activity because the results are posted in onActivityResult. In order to decouple you GoogleSingInWrapper from all your Activities you could create a dedicated Activity to manage all onActivityResults. This activity should be transparent and will be invisible for the user.
You can achieve that with this code:
public class GoogleActivity extends AppCompatActivity {
public static final int RC_SIGN_IN = 1000;
private static final String ACTION = "calling_action";
public static Intent getIntent(Context context, int action, Intent actionIntent) {
Intent i = new Intent(context, GoogleActivity.class);
i.putExtra(ACTION, action);
i.putExtra(Intent.EXTRA_INTENT, actionIntent);
return i;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Intent actionIntent;
int action = getIntent().getIntExtra(ACTION, 0);
switch (action) {
case RC_SIGN_IN:
actionIntent = (Intent) getIntent().getExtras().get(Intent.EXTRA_INTENT);
if (actionIntent != null)
startActivityForResult(actionIntent, RC_SIGN_IN);
break;
case 0:
default:
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RC_SIGN_IN:
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
finish();
return;
}
}
}
Then set the transparent theme in the manifest for this Activity:
<activity
android:name=".data.drive.GoogleActivity"
android:theme="#style/TransparentActivity"/>
And define your transparent style in your values folder:
<style name="TransparentActivity" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">#android:color/transparent</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
Now you have to catch all pieces I've done and construct your final product in order to get it working.
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.
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);
I am attempting to check if the user is signed in and weather or not they are, send them to the login or keep them on the main activity.
Main Activity
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
public class MainActivity extends Activity {
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Plus.API, null).addScope(Plus.SCOPE_PLUS_LOGIN).build();
if (!mGoogleApiClient.isConnected()) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
LoginActivity
package com.alfalfa.thisthat;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
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.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.plus.Plus;
public class LoginActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener, OnClickListener {
private static final int RC_SIGN_IN = 0;
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignInClicked;
private static SignInButton mSignInButton;
private ConnectionResult mConnectionResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
mSignInButton.setOnClickListener(this);
mSignInButton.setEnabled(true);
mSignInButton.setSize(SignInButton.SIZE_WIDE);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.sign_in_button
&& !mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInErrors();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!mIntentInProgress) {
mConnectionResult = result;
if (mSignInClicked) {
resolveSignInErrors();
}
}
}
private void resolveSignInErrors() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle connectionHint) {
mSignInClicked = false;
navigateToMainActivity();
Toast.makeText(this, "User is connected!", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
}
public void navigateToMainActivity() {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
}
When I start the app, it loads into the login screen. When I click the sign in button, the app backs in and our of the LoginActivity infinitely.
I removed a piece of code from my app that does something similar. It is Google Drive related, but easy to adapt.
On menu selection, it pops-up account picker and connects to GAC with the selected account.
Checking if the user is signed-in is irrelevant in my situation. If there has been a valid user connected before, the connect() is successful, otherwise the account picker pops-up. There is more about it in SO 21610239. And I believe there is no way to get current signed user, unless you pop-up the account picker and get it from the return (KEY_ACCOUNT_NAME below).
public class SomeActivity extends Activity
implements ConnectionCallbacks, OnConnectionFailedListener {
GoogleApiClient mGAC;
// from menu: user pops up account picker and selects account
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.acc_select:
Intent intent = AccountPicker.newChooseAccountIntent(null, null,
new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, false, null, null, null, null);
startActivityForResult(intent, AUTH_REQUEST);
return true;
}
return super.onOptionsItemSelected(item);
}
// back from account picker (invoked from menu OR from onConnectionFailed())
#Override protected void onActivityResult(final int rqst, final int rslt, final Intent it) {
switch (rqst) {
case AUTH_REQUEST:
if (mGAC == null) {
mGAC = new GoogleApiClient.Builder(this).addApi(Drive.API).addScope(Drive.SCOPE_FILE)
.setAccountName(it.getStringExtra(AccountManager.KEY_ACCOUNT_NAME))
.addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
if ((mGAC != null) && !mGAC.isConnected())
mGAC.connect();
break;
}
}
// connection failed, either fatal, or needs account / authorization
#Override public void onConnectionFailed(ConnectionResult rslt) {
if (!rslt.hasResolution()) { // FATAL ------->>>>
Toast.makeText(this, "FAILED", Toast.LENGTH_LONG).show();
} else try { // needs authorization
rslt.startResolutionForResult(this, AUTH_REQUEST);
} catch (SendIntentException e) {}
}
#Override public void onConnected(Bundle connectionHint) {
// do my stuff here
}
#Override public void onConnectionSuspended(int i) {}
}
There's one glaring issue I see in the code you posted:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Plus.API, null).addScope(Plus.SCOPE_PLUS_LOGIN).build();
if (!mGoogleApiClient.isConnected()) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
At this point mGoogleApiClient will never be connected. To determine if the user isn't successfully connected (there are a number of reasons this could happen), you want to add an OnConnectionFailedListener to the Builder, then call .connect() on mGoogleApiClient and wait for OnConnectionFailedListener#onConnectionFailed() to be called. If that happens, then redirect the user back to the login Activity.
I am trying to signin to to my app using Google+ play services.The code doesn't have any errors and it launches in the emulator.But when i click the "signin with google" button i get this error in the logcat
I am not sure why this happens.Here is my MainActivity class:
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.util.Log;
import android.view.*;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.*;
import com.google.android.gms.common.GooglePlayServicesClient.*;
import com.google.android.gms.plus.PlusClient;
public class MainActivity extends Activity implements View.OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener{
private static final String TAG = "MainActivity";
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private Button signInButton;
private ProgressDialog mConnectionProgressDialog;
private static PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlusClient = new PlusClient.Builder(this, this, this)
.setActions("http://schemas.google.com/AddActivity", "http://schemas.google.com/ BuyActivity")
.setScopes("PLUS_LOGIN") // Space separated list of scopes
.build();
// Progress bar to be displayed if the connection failure is not resolved.
mConnectionProgressDialog = new ProgressDialog(this);
mConnectionProgressDialog.setMessage("Signing in...");
signInButton =(Button) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(this);
}
public static PlusClient getPlusClientObject() {
return mPlusClient;
}
protected void onStart() {
super.onStart();
mPlusClient.connect();
}
protected void onStop() {
super.onStop();
mPlusClient.disconnect();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
//signInButton =(Button) findViewById(R.id.sign_in_button);
//signInButton.setOnClickListener(this);
return true;
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
// The user clicked the sign-in button already. Start to resolve
// connection errors. Wait until onConnected() to dismiss the
// connection dialog.
if (result.hasResolution()) {
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
// Save the result and resolve the connection failure upon a user click.
mConnectionResult = result;
}
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
#Override
public void onConnected(Bundle connectionHint) { //this is called when the user has successfully signed in
String accountName = mPlusClient.getAccountName();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
Intent logoutIntention = new Intent(this, LogoutActivity.class);
startActivity(logoutIntention);
}
#Override
public void onDisconnected() {
Log.d(TAG, "disconnected");
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.sign_in_button && !mPlusClient.isConnected()) {
if (mConnectionResult == null) {
mConnectionProgressDialog.show();
} else {
try {
mConnectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
// Try connecting again.
mConnectionResult = null;
mPlusClient.connect();
}
}
}
}
}
and my app references google-play-services_lib which has this structure:
I am not sure why this is happening.Can anyone help?
Here is the definition of my emulator: