首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >谷歌在android注册

谷歌在android注册
EN

Stack Overflow用户
提问于 2018-12-05 04:59:43
回答 3查看 2.5K关注 0票数 0

为了创建一个JSON文件,我正在使用Google帐户登录。此外,我还将JSON文件与我的project.But集成在一起,我得到了account.getDisplayName抛出nullPointException的异常。

谷歌登录代码:

代码语言:javascript
运行
复制
public class MainActivity extends AppCompatActivity implements 
View.OnClickListener,GoogleApiClient.OnConnectionFailedListener {
private SignInButton signInButton;
private GoogleApiClient client;
private static final int REQ_CODE = 9001;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    signInButton = (SignInButton)findViewById(R.id.btn_signin);

    GoogleSignInOptions options = new 
 GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
            .requestProfile()
            .requestEmail()
            .build();
    client = new GoogleApiClient.Builder(this).
            enableAutoManage(this,this).
            addApi(Auth.GOOGLE_SIGN_IN_API,options).build();

    signInButton.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.btn_signin:
            signIn();
            break;
    }
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
    public void signIn(){
    Intent intent = Auth.GoogleSignInApi.getSignInIntent(client);
    startActivityForResult(intent,REQ_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable 
Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQ_CODE){
        GoogleSignInResult result = 
Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleResult(result);
    }
}

 private void handleResult(GoogleSignInResult result) {
    if (result.isSuccess()){
        GoogleSignInAccount account = result.getSignInAccount();
        String name = account.getDisplayName();
            String email = account.getEmail();
            String image = account.getPhotoUrl().toString();
    }
}
}

这是我的编译库:

代码语言:javascript
运行
复制
implementation 'com.google.android.gms:play-services-auth:16.0.1'

请指导我做错了什么

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-12-05 05:05:21

试试这个:

代码语言:javascript
运行
复制
    @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 == REQ_CODE) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);

            // G+
            Person person  = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
            System.out.println("Display Name: " + person.getDisplayName());
            System.out.println("Gender: " + person.getGender());
            System.out.println("AboutMe: " + person.getAboutMe());
            System.out.println("Birthday: " + person.getBirthday());
            System.out.println("Current Location: " + person.getCurrentLocation());
            System.out.println("Language: " + person.getLanguage());

        }
    }
票数 1
EN

Stack Overflow用户

发布于 2018-12-05 05:13:19

如果你想要谷歌的“UserName,电子邮件Id,个人资料网址,谷歌Id”。

你犯了"GoogleSignInOptions“的错误。请用您的GoogleSignInOptions代码替换我的GoogleSignInOptions,以解决您的问题。

然后,您的解决方案在这里, ->,您应该遵循下面的代码。

代码语言:javascript
运行
复制
    private GoogleApiClient mGoogleApiClient;
    private static final int RC_SIGN_IN = 9001;
    private LinearLayout googleBtn;

        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
           View view = inflater.inflate(R.layout.fragment_login, container, false);
           googleBtn = view.findViewById(R.id.googleBtn);


           GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail()
                    .requestIdToken(getString(R.string.default_web_client_id))
                    .build();

           mGoogleApiClient = new GoogleApiClient.Builder(Objects.requireNonNull(getActivity()))
                .enableAutoManage(getActivity(), 0, connectionResult -> {
                    Snackbar.make(googleBtn, "Connection failed..", Snackbar.LENGTH_SHORT).show();
                    Log.e(TAG, "Google connection Error: " + connectionResult.getErrorMessage());
                })
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(@Nullable Bundle bundle) {
                        //Log.e(TAG,"mGoogleApiClient is connected");
                        mGoogleApiClient.clearDefaultAccountAndReconnect();
                    }

                    @Override
                    public void onConnectionSuspended(int i) {

                    }
                })
                .build();
            }

        public void onClick(View v) {
        switch (v.getId()) {
               case R.id.googleBtn:
                       //stopAutoManage first otherwise throws exception Already managing a GoogleApiClient with id 0
                         if (mGoogleApiClient != null) {
        mGoogleApiClient.stopAutoManage(Objects.requireNonNull(getActivity()));
                         }
                loginWithGoogle();
                break;
         }

    public void loginWithGoogle() {
        Log.e(TAG, "is connected? " + mGoogleApiClient.isConnected());

        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        Objects.requireNonNull(getActivity()).startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
    }


public void handleSignInResult(GoogleSignInResult result) {

        if (result.isSuccess()) {
            GoogleSignInAccount acct = result.getSignInAccount();
            // Get account information

            if (acct != null) {
                Name = acct.getDisplayName();
                if (acct.getEmail() != null) {
                    Email = acct.getEmail();
                } else {
                    Email = "";
                }

                SocialUserId = acct.getId();
                Gender = "";

                String idToken = acct.getIdToken();
                String profileURL = Objects.requireNonNull(acct.getPhotoUrl()).toString();

                String status = "Status: \nFullname: " + Name + "\n Email: " + Email + "\nProfile URI: " + profileURL;
                Log.i(TAG, "Google signin " + status);
                Log.i(TAG, "ID Token: " + idToken);
                Log.i(TAG, "ID: " + acct.getId());

                //TODO Temporary "acct.getCompId()" pass "idToken"

                checkIsUserExists();
            }

        } else {
            hideProgressBar();
            Log.e(TAG, "Failed!! Google Result " + result.getStatus());

            int status_code = result.getStatus().getStatusCode();
            switch (status_code) {
                case GoogleSignInStatusCodes.SIGN_IN_CANCELLED:
                    Snackbar.make(googleBtn, "Google sign in has been cancelled.", Snackbar.LENGTH_SHORT).show();
                    break;
                case GoogleSignInStatusCodes.NETWORK_ERROR:
                    Snackbar.make(googleBtn, "Application is unable to connect with internet", Snackbar.LENGTH_SHORT).show();
                default:
                    //AppUtils.showSnackBar(LandingActivity.this, btnLogin, GoogleSignInStatusCodes.getStatusCodeString(result.getStatus().getStatusCode()), R.integer.snackbar_duration_3sec);
                    break;
            }
        }
    }
票数 0
EN

Stack Overflow用户

发布于 2020-02-07 07:19:27

您可以按照以下步骤将Google登录集成到Android应用程序中。

步骤1.实现库

代码语言:javascript
运行
复制
 implementation 'com.google.android.gms:play-services-auth:17.0.0'

步骤2.添加google登录按钮

代码语言:javascript
运行
复制
<com.google.android.gms.common.SignInButton
    android:id="@+id/sign_in_button"
    android:layout_width="wrap_content"
    android:layout_gravity="center|center_vertical"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    />

步骤3.在活动中添加下面的代码。

代码语言:javascript
运行
复制
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    signup = (SignInButton)findViewById(R.id.signup);
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    signup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent signInIntent = mGoogleSignInClient.getSignInIntent();
            startActivityForResult(signInIntent, google_login);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Log.e("called", "called");
    if (requestCode == google_login) {
        Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
        handleSignInResult(task);
    }
}

private void handleSignInResult(Task completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);
        // Disaplay data on your screen
        Log.e("email", account.getEmail());
        Log.e("name", account.getDisplayName());
        Log.e("id", account.getId());

    } catch (ApiException e) {
        // The ApiException status code indicates the detailed failure reason.
        // Please refer to the GoogleSignInStatusCodes class reference for more information.
        Log.e("signInResult", ":failed code=" + e.getStatusCode());
    }
}

您可以按照本教程完成实现:- 在Android应用程序中使用Google登录

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53625430

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档