当我尝试从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();
}
最佳答案
尝试这个...
限定:
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();
现在在登录按钮上设置点击监听器
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();
}
});
}
希望这会帮助你。
关于java - 当我尝试从GoogleApiClient注销时,在空对象引用上收到错误消息GoogleApiClient.isConnected(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42128362/