当我尝试从GoogleApiClient
退出时,收到以下错误消息
GoogleApiClient.isConnected() on a null object reference
这是我的代码:
public static GoogleSignInOptions gso;
public static GoogleApiClient mGoogleApiClient;
//.........
google.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
mGoogleApiClient = new GoogleApiClient.Builder(getContext()).enableAutoManage(getActivity(), new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(getContext(), "Login failed", Toast.LENGTH_LONG).show();
}
}).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
Intent intent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(intent, requestCode);
mGoogleApiClient.connect();
Toast.makeText(getContext(),"User Name "+ acc.getDisplayName()+ "Mail "+acc.getEmail(), Toast.LENGTH_LONG).show();
}
});
和我的退出代码
public void signout(){
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
Intent intent1 = new Intent(getContext(),LoginActivity.class);
startActivity(intent1);
getActivity().finish();
}
});
我也尝试过:
if (UserLogin.mGoogleApiClient.isConnected()) {
UserLogin.mGoogleApiClient.disconnect();
}
答案 0 :(得分:0)
试试这个......
定义:
public GoogleSignInOptions gso;
public GoogleApiClient mGoogleApiClient;
在Oncreate方法中初始化:
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
mGoogleApiClient.connect();
现在在signIn按钮上设置点击监听器
google.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(intent, requestCode);
Toast.makeText(getContext(),"User Name "+ acc.getDisplayName()+ "Mail "+acc.getEmail(), Toast.LENGTH_LONG).show();
}
});
/////
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(getContext(), "Login failed", Toast.LENGTH_LONG).show();
}
//退出
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
Intent intent1 = new Intent(getContext(),LoginActivity.class);
startActivity(intent1);
getActivity().finish();
}
});
}
希望这会对你有所帮助。