android - 作业帮助 - 多个 Activity 传递 Intent

标签 android

我试图将一些信息从我的第二个 Activity 传递到第一个 Activity 一半正在发送,但我似乎无法弄清楚为什么另一半不工作。因此,例如在第二个 Activity 中,一旦用户看到他们必须支付的总金额。他们可以选择通过单选按钮以“现金”或“信用卡”支付。如果用现金,它会回到第一个 Activity ,显示他们必须支付的金额。如果他们选择信用卡,则交易有 50% 的可能性无法通过(网络不佳)并在第一个 Activity 中显示错误消息。我尝试通过使用来自 (0, 1) 的随机数生成器来执行此操作,如果 rng 为 0,则交易成功,目前正在运行。如果 rng 为 1,则交易不成功。这是我目前需要的帮助,因为它目前没有显示不成功的交易。

在此先感谢大家对我的帮助!

最佳答案

根据您的逻辑代码,在 SecondActivity 类中,您可以将 credit() 方法更改为

private void credit() {
    Random rand = new Random();
    int randnum = rand.nextInt( (1) + 1 );
    Intent intentResult = new Intent();
    String totalCost = "Total is: " + totalString + " inc. HST";
    if (randnum == 0) {
        intentResult.putExtra( "total", "Payment accepted.\n" + totalCost);
    } else {
        // Pass back total cost in case payment is not successful.
        intentResult.putExtra( "error", "Payment not accepted!\n" + totalCost); 
    }
    setResult( RESULT_OK, intentResult);
    finish();
    Toast.makeText( SecondActivity.this, "Random #: " + randnum, Toast.LENGTH_LONG ).show();
}

并在 MainActivity 中

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            String total = data.getStringExtra("total");
            String error = data.getStringExtra("error");

            if (total != null) {
                txtDisplay.setText(total);
            } else if (error != null) {
                txtDisplay.setText(error);
            } else {
                // Something goes wrong!!!
            }
        }
    }
}

关于android - 作业帮助 - 多个 Activity 传递 Intent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58177144/

相关文章:

java - 如何使用 RxJava 过滤列表并对所有匹配的元素进行分组

Android VPNService - 如何从我的 Activity 中调出 'system-managed dialog'?

Android - Gridview 图像在滚动时混合

android - 为什么 URLConnection 会在 6 分钟以上而不是 5 秒后超时?

android - 使用 ActionBarSherlock;遇到 2.2 和 ICS/JB 之间的 View.getLocationOnScreen() 不一致问题

android - 意外的 grpc 使用地理编码器失败

Android Proguard 和 FirebaseListAdapter 冲突

Android:测试运行失败:由于 'java.lang.IncompatibleClassChangeError',仪器运行失败

android - 退格键仅删除 TextField 中的一个字母

java - android gradle packageAllDebugClassesForMultiDex