This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Here is my SignInActivityCode
public class SignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {
GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN=0;
private String TAG = "SignInActivity";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signin_activity);
try{
getSupportActionBar().hide();
}catch (Exception e){
e.printStackTrace();
}
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();
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_STANDARD);
signInButton.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.sign_in_button:
signIn();
break;
}
}
private void signIn(){
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
protected 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);
handleSignInIntent(result);
}
}
private void handleSignInIntent(GoogleSignInResult result){
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if(result.isSuccess()){
GoogleSignInAccount acct = result.getSignInAccount();
Toast.makeText(this, "Sign in successful!", Toast.LENGTH_LONG).show();
setDefaults(acct.getDisplayName(), acct.getEmail(), acct.getIdToken());
Intent intent = new Intent(SignInActivity.this, MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(this, "Sign In Failed!\nPlease try again.", Toast.LENGTH_LONG).show();
}
}
public void setDefaults(String name, String email, String token){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("userName", name);
editor.putString("userEmail", email);
editor.putString("userIdToken", token);
editor.apply();
}
}
and here is how I am applying the information passed to the MainActivity in my nav_header_main.xml file
#Override
protected void onCreate(Bundle savedInstanceState) {
initializeUserInfo();
}
private void initializeUserInfo() {
userName = (TextView) findViewById(R.id.nav_user_name_tv);
userEmail = (TextView) findViewById(R.id.nav_user_email_tv);
final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
name = sharedPref.getString("userName", "");
email = sharedPref.getString("userEmail", "");
try{
userName.setText(name);
userEmail.setText(email);
}catch(Exception e){
e.printStackTrace();
}
}
and the error that I am getting in the logs
Blockquote
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
This is how you initialize and declare navigation view items
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
// Navigation view header
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.nameNav);
Related
Okey. I integrated a google sign in feature in my android app.
This is my login activity
public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
//button
private SignInButton signInButton;
//options
private GoogleSignInOptions gso;
//client api
private GoogleApiClient mGoogleApiClient;
private static final int LCD = 4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_login);
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();
signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(intent,LCD);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == LCD){
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result) {
//check if the operation is successful
if(result.isSuccess()){
goMainScreen();
}else {
Toast.makeText(this,"Something went wrong",Toast.LENGTH_SHORT).show();
}
}
private void goMainScreen() {
Intent secondActivity = new Intent(this, ProfileActivity.class);
secondActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(secondActivity);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Once, login is successful, i open Profile activity, and get the user image and the name
ProfileActivity
public class ProfileActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
private ImageView photo;
private TextView name;
private GoogleApiClient googleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
photo = (ImageView) findViewById(R.id.profileImage);
name = (TextView) findViewById(R.id.theName);
GoogleSignInOptions gsp = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this,this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gsp)
.build();
}
#Override
protected void onStart() {
super.onStart();
OptionalPendingResult<GoogleSignInResult> optionalPendingResult = Auth.GoogleSignInApi.silentSignIn(googleApiClient);
if(optionalPendingResult.isDone()){
GoogleSignInResult sig = optionalPendingResult.get();
handleSigninResult(sig);
}else {
optionalPendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(#NonNull GoogleSignInResult googleSignInResult) {
handleSigninResult(googleSignInResult);
}
});
}
}
private void handleSigninResult(GoogleSignInResult sig) {
if(sig.isSuccess()){
GoogleSignInAccount acc = sig.getSignInAccount();
//accessing the data
name.setText(acc.getDisplayName());
//image with glide
Glide.with(this).load(acc.getPhotoUrl()).into(photo);
}else {
//in case is not successful
//send the user to the Login Screen
goLoginInScree();
}
}
private void goLoginInScree() {
Intent goUser = new Intent(this, LoginActivity.class);
goUser.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(goUser);
}
#Override
public void onConnectionFailed( ConnectionResult connectionResult) {
}
My next issue is, how do i implement feature for automatically login in, if the user is already been logged to the activity? I don't want every time app is open, to click Sign in button, but directly to go to profile activity.
After Login Success in google Authentication, store the result in shared preferences.
private void handleSigninResult(GoogleSignInResult sig) {
if(sig.isSuccess()){
GoogleSignInAccount acc = sig.getSignInAccount();
//accessing the data
name.setText(acc.getDisplayName());
SharedPreferences prefs = getSharedPreferences("shared_pref_name", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("email", acc.getEmail());
editor.putInt("name", acc.getDisplayName());
editor.putBoolean("hasLogin",true);
editor.apply();
//image with glide
Glide.with(this).load(acc.getPhotoUrl()).into(photo);
}else {
//in case is not successful
//send the user to the Login Screen
goLoginInScree();
}
}
Note: Clear the Shared Preference when user logouts
the easiest way is using SharedPreferences
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
after successfully login using Google+, save the credentials detail in Sharedpreferences
SharedPreferences.Editor editor = prefs.edit();
editor.putString("email", acc.getEmail());
editor.putInt("name", acc.getDisplayName());
editor.putBoolean("hasLogin",true); // set the prefs true after success login
editor.apply();
then, you can check if user is first time login or not
if(prefs.getBoolean("hasLogin")){
//no need to sigin again.. proceeed to your activity
}
else{
//need to sign in
}
if user want to logout, just revoke Access google sign in including set the prefs "hasLogin" to "false"
I want to integrate Google sign in to my game. But i don't want to make sign in process with a button I want it happen once user opens application.
Whenever MenuActivity is created it asks to choose an account to sign in. But I want it to choose account only once (first time) and remember every time. Here is code:
public class MenuActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private static final String TAG = MainActivity.class.getSimpleName();
private static final int RC_SIGN_IN = 007;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
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();
if(!mGoogleApiClient.isConnected()){
signIn();
}
}
public void startGame(View view){
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#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 onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
} else {
}
}
}
First create SharedPreferences
public void saveUser (String key, String value ) {
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, value);
editor.commit();
}
public String getUser (String key) {
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
return pref.getString(key, "");
}
Check user's email if it is empty add SharedPreferences
if(!mGoogleApiClient.isConnected() && getUser("email").isEmpty() ){
signIn();
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
saveUser("email", acct.getEmail());
saveUser("name", acct.getDisplayName());
} else {
}
}
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;
private Button btnSignOut, btnRevokeAccess;
private LinearLayout llProfileLayout;
private ImageView imgProfilePic;
private TextView txtName, txtEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignOut = (Button) findViewById(R.id.btn_sign_out);
btnRevokeAccess = (Button) findViewById(R.id.btn_revoke_access);
llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
txtName = (TextView) findViewById(R.id.txtName);
txtEmail = (TextView) findViewById(R.id.txtEmail);
btnSignIn.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
btnRevokeAccess.setOnClickListener(this);
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());
}
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();
Log.e(TAG, "display name: " + acct.getDisplayName());
String personName = acct.getDisplayName();
String personPhotoUrl = acct.getPhotoUrl().toString();
String email = acct.getEmail();
Log.e(TAG, "Name: " + personName + ", email: " + email
+ ", Image: " + personPhotoUrl);
txtName.setText(personName);
txtEmail.setText(email);
Glide.with(getApplicationContext()).load(personPhotoUrl)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgProfilePic);
updateUI(true);
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_sign_in:
signIn();
break;
case R.id.btn_sign_out:
signOut();
break;
case R.id.btn_revoke_access:
revokeAccess();
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);
}
private void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
private void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.hide();
}
}
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
btnRevokeAccess.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
btnRevokeAccess.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.GONE);
}
}
}
Please give me in detail answer about why we use The constant in this
Why we use A Constant int RC_SIGN_IN = 007
private static final int RC_SIGN_IN = 007
There could be many activities which you can start to get some sort of result from an activity and you receive those results in only one method of the activity i.e onActivityResult().
In order to differentiate which type of result you have received you make use of Request codes, which is in-fact just a unique constant integer.
So When the Google sign in process returns the sign-in result (success or failure) it returns using the request code so that you can check the result which you just received is a Sig-in result and get the data in the required data type.
I am unable to signup in google plus in my android application. It is working fine in jelly bean and kitkat. It is not working in lollypop and above.
I am getting false in GoogleSignInResult result.success().
Below is my Code:
public class SignUp extends FragmentActivity implements
GoogleApiClient.OnConnectionFailedListener {
private ImageView google_button
private GoogleApiClient mGoogleApiClient;
private static final String TAG = "SignInActivity";
private static final int RC_SIGN_IN = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestProfile()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
//initializes view
initializeViews();
//facebook login end
google_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
Log.e("data g+", result.toString());
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result) {
Log.e(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
Log.e("authType", "googlePlus");
Log.e("authId", acct.getId());
Log.e("firstname", acct.getDisplayName());
Log.e("middlename", acct.getDisplayName());
Log.e("lastname", acct.getDisplayName());
Log.e("userpic", acct.getPhotoUrl() + "");
Log.e("email", acct.getEmail());
String[] DisplayName = acct.getDisplayName().split(" ");
String firstName = "";
String lastName = "";
if (DisplayName.length == 2) {
firstName = DisplayName[0];
lastName = DisplayName[1];
} else {
firstName = acct.getDisplayName();
}
String photoUrl = "";
if (acct.getPhotoUrl() != null) {
photoUrl = acct.getPhotoUrl().toString();
}
Bundle data = new Bundle();
data.putString("authType", "googlePlus");
data.putString("authId", acct.getId());
data.putString("firstname", firstName);
data.putString("middlename", "");
data.putString("lastname", lastName);
data.putString("userpic", photoUrl);
data.putString("email", acct.getEmail());
Intent intent = new Intent(SignUp.this, Register.class);
intent.putExtras(data);
startActivity(intent);
finish();
} else {
// Signed out, show unauthenticated UI.
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
public void initializeViews() {
register = (TextView) findViewById(R.id.register);
fb_button = (ImageView) findViewById(R.id.facebook_button);
google_button = (ImageView) findViewById(R.id.google_button);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e("connectionResult", connectionResult.toString());
Toast.makeText(getApplicationContext(), getResources().getString(R.string.server_error), Toast.LENGTH_SHORT).show();
}
}
Am implementing google sign in my android application,in that i can log in using the google sign in after the success log in ,i want redirect from login page to my homepageactvity.But from the Home page activity i can log out (disconnect Google api client),when clicking the log out button again the Homepageactvity is coming..pls help me to figure this issue. My Login actvity is below
public class LoginActivityGoogle extends Activity implements OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
// Google client to communicate with Google
private GoogleApiClient mGoogleApiClient;
private String TAG = "Login";
private boolean mIntentInProgress;
private boolean signedInUser;
private ConnectionResult mConnectionResult;
private SignInButton signinButton;
private ImageView image;
private TextView username, emailLabel;
private LinearLayout profileFrame, signinFrame;
SessionManager session;
private boolean mSignInClicked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_google);
signinButton = (SignInButton) findViewById(R.id.signin);
signinButton.setOnClickListener(this);
image = (ImageView) findViewById(R.id.image);
username = (TextView) findViewById(R.id.username);
emailLabel = (TextView) findViewById(R.id.email);
profileFrame = (LinearLayout) findViewById(R.id.profileFrame);
signinFrame = (LinearLayout) findViewById(R.id.signinFrame);
session = new SessionManager(getApplicationContext());
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(new Scope(Scopes.PROFILE))
.addScope(new Scope(Scopes.EMAIL))
.build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
if (!mIntentInProgress) {
// store mConnectionResult
mConnectionResult = result;
if (signedInUser) {
resolveSignInError();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
if (requestCode == RC_SIGN_IN) {
// If the error resolution was not successful we should not resolve further.
if (resultCode != RESULT_OK) {
signedInUser = false;
}
signedInUser = false;
mGoogleApiClient.connect();
}
}
#Override
public void onConnected(Bundle arg0) {
signedInUser = false;
Toast.makeText(this, "Connected", Toast.LENGTH_LONG).show();
// To launch from gere to homwpageactivity
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Intent in = new Intent(getApplicationContext(), HomePageActivity.class);
in.putExtra("username",personName);
in.putExtra("email",email);
in.putExtra("profile_pic",personPhotoUrl);
startActivity(in);
getProfileInformation();
}
private void updateProfile(boolean isSignedIn) {
if (isSignedIn) {
signinFrame.setVisibility(View.GONE);
// profileFrame.setVisibility(View.VISIBLE);
} else {
signinFrame.setVisibility(View.VISIBLE);
//profileFrame.setVisibility(View.GONE);
}
}
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
updateProfile(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
updateProfile(false);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.signin:
googlePlusLogin();
break;
}
}
public void signIn(View v) {
googlePlusLogin();
}
private void googlePlusLogin() {
if (!mGoogleApiClient.isConnecting()) {
signedInUser = true;
resolveSignInError();
}
}
private void googlePlusLogout() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateProfile(false);
}
}
// download Google Account profile image, to complete profile
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView downloadedImage;
public LoadProfileImage(ImageView image) {
this.downloadedImage = image;
}
protected Bitmap doInBackground(String... urls) {
String url = urls[0];
Bitmap icon = null;
try {
InputStream in = new java.net.URL(url).openStream();
icon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return icon;
}
protected void onPostExecute(Bitmap result) {
downloadedImage.setImageBitmap(result);
}
}
And My homepageactvity is
public class HomePageActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,View.OnClickListener,
GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener
{
private SharedPreferences preferences;
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
cd = new ConnectionDetector(this);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
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 = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header=navigationView.getHeaderView(0);
TextView username=(TextView) header.findViewById(R.id.username);
TextView user_email=(TextView) header.findViewById(R.id.email);
ImageView profileImage=(ImageView) header.findViewById(R.id.imageView) ;
String user_name= getIntent().getStringExtra("username");
String user_gmail= getIntent().getStringExtra("email");
String profile_pic=getIntent().getStringExtra("profile_pic");
username.setText(user_gmail);
user_email.setText(user_name);
CardView card_attendance = (CardView) findViewById(R.id.card_attendance);
CardView card_assignment = (CardView) findViewById(R.id.card_assignment);
CardView card_circular = (CardView) findViewById(R.id.card_circular);
CardView card_communication = (CardView) findViewById(R.id.card_communication);
CardView card_Fee = (CardView) findViewById(R.id.card_Fee);
CardView card_Library = (CardView) findViewById(R.id.card_Library);
CardView card_Result = (CardView) findViewById(R.id.card_Result);
CardView card_StudyMat = (CardView) findViewById(R.id.card_StudyMat);
card_attendance.setOnClickListener(this);
card_assignment.setOnClickListener(this);
card_circular.setOnClickListener(this);
card_communication.setOnClickListener(this);
card_Fee.setOnClickListener(this);
card_Library.setOnClickListener(this);
card_Result.setOnClickListener(this);
card_StudyMat.setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(new Scope(Scopes.PROFILE))
.addScope(new Scope(Scopes.EMAIL))
.build();
}
#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_change_pass) {
Intent intent = new Intent(HomePageActivity.this, ChangePasswordActivity.class);
startActivity(intent);
} else if (id == R.id.nav_logout) {
googlePlusLogout();
}
else if (id == R.id.nav_faq) {
Intent intent = new Intent(HomePageActivity.this, FAQActivity.class);
startActivity(intent);
} else if (id == R.id.nav_about) {
PopupAbout();
} else if (id == R.id.nav_share) {
shareApp();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.card_attendance:
Intent intent = new Intent(HomePageActivity.this, AttendanceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case R.id.card_assignment:
Intent intent2 = new Intent(HomePageActivity.this, AssignmentActivity.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent2);
break;
case R.id.card_StudyMat:
Intent intent3 = new Intent(HomePageActivity.this, StudyMaterialListActivity.class);
intent3.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent3);
break;
case R.id.card_Library:
Intent intent4 = new Intent(HomePageActivity.this, LibraryActivity.class);
intent4.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent4);
break;
case R.id.card_Result:
Intent intent5 = new Intent(HomePageActivity.this, ResultActivity.class);
intent5.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent5);
break;
case R.id.card_communication:
Intent intent6 = new Intent(HomePageActivity.this, CommunicationActivity.class);
intent6.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent6);
break;
case R.id.card_Fee:
Intent intent7=new Intent(HomePageActivity.this,FeeActivity.class);
intent7.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent7);
break;
case R.id.card_circular:
Intent intent8=new Intent(HomePageActivity.this,CircularListActivity.class);
intent8.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent8);
break;
default:
break;
}
}
private void shareApp() {
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Checkout The NI Model School App for Android");
String sAux = "\nHi, I am using The NI Model School Android app to track my child's activities in school.\n";
String sAux1 = sAux + "Why don't you check it out on your Android phone.\n";
String sAux2 = sAux1 + "market://details?id="
+ HomePageActivity.this.getPackageName() + "\n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux2);
startActivity(Intent.createChooser(i, "choose one"));
} catch (Exception e) {
e.printStackTrace();
}
}
private void PopupAbout() {
AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(
HomePageActivity.this);
alertDialogBuilder1.setTitle(R.string.app_name);
LayoutInflater li = LayoutInflater.from(HomePageActivity.this);
final View pView = li.inflate(R.layout.alert_about, null);
alertDialogBuilder1.setView(pView);
alertDialogBuilder1.setIcon(R.mipmap.ic_launcher);
alertDialogBuilder1.setCancelable(true);
try {
PackageInfo pInfo = HomePageActivity.this.getPackageManager()
.getPackageInfo(HomePageActivity.this.getPackageName(), 0);
String version = pInfo.versionName;
alertDialogBuilder1.setMessage("Version: " + version);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
alertDialogBuilder1.setPositiveButton("Rate",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
Uri uri = Uri.parse("market://details?id="
+ HomePageActivity.this.getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY
| Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
Toast.makeText(HomePageActivity.this,
"Play Store unavailable..",
Toast.LENGTH_LONG).show();
}
}
});
AlertDialog alertDialog = alertDialogBuilder1.create();
alertDialog.show();
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
} private void googlePlusLogout() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
Intent intent = new Intent(HomePageActivity.this, LoginActivityGoogle.class);
startActivity(intent);
}
}
remove the selected line in image from your code
I resolved the above issue,actually the app got crashr=ed because i didn't connect google client in to my Homepageactvity.So once i coonected the google client in to my Homepageactvity,then i can log out from my app.
First i intailthe below codes in to my On create method
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
After that i called the method for googlesignout.Its working fine now