【问题标题】:How to add two override onActivityResult methods in one java activity?如何在一个 java 活动中添加两个覆盖 onActivityResult 方法?
【发布时间】:2023-03-15 15:05:01
【问题描述】:

我无法在一个 java 活动中使用两个覆盖 onActivityResult 方法。我尝试了循环,但在此使用循环没有任何意义。我附上代码帮助我解决这个问题。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        Intent home = new Intent(this, HomeActivity.class);
        startActivity(home);
    } else {
        Toast.makeText(getApplicationContext(), "Unable to login please check your internet connection", Toast.LENGTH_LONG).show();
    }
}};

@Override
public 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 handleSignInResult(Task<GoogleSignInAccount> completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);
        startActivity(new Intent(LoginActivity.this, HomeActivity.class));
    } catch (ApiException e) {
        Log.w("Google Sign In Error", "signInResult:failed code=" + e.getStatusCode());
        Toast.makeText(LoginActivity.this, "Failed", Toast.LENGTH_LONG).show();
    }
}

@Override
protected void onStart() {
    GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
    if(account != null) {
        startActivity(new Intent(LoginActivity.this, HomeActivity.class));
    }
    super.onStart();
}

【问题讨论】:

  • 我是 stackoverflow 和编码的新手,所以请原谅我的错误 :)
  • 你不能两次声明相同的方法名和签名,或者两次覆盖一个方法。只需处理所有场景,例如:switch(requestCode) { } 语句或覆盖方法 onActivityResult 方法中的 if(requestCode == RC_SIGN_IN) { ... } else if (resultCode == RESULT_OK) { ... } else { .. }

标签: java android firebase facebook android-studio


【解决方案1】:

你不能多次覆盖同一个方法,这样做实际上没有意义。

只需覆盖一次并执行简单的if statements 即可检查:

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

    if (resultCode == RESULT_OK && requestCode != RC_SIGN_IN) {
        Intent home = new Intent(this, HomeActivity.class);
        startActivity(home);

    }else if(requestCode == RC_SIGN_IN){

        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        handleSignInResult(task);

    } else {

        Toast.makeText(getApplicationContext(), "Unable to login please check your internet connection", Toast.LENGTH_LONG).show();

    }
}

【讨论】:

  • 非常感谢你们两位的回答,我的应用程序启动并运行了
猜你喜欢
  • 2021-07-20
  • 2020-05-05
  • 2015-01-12
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多