将 Bundle 转换为整数(意图)

Convert Bundle to Integer (Intents)

我正在尝试通过一个 intent 将一个 int 传递给另一个 class 并成功地通过了整数,但是我不确定如何将 Bundle 转换为 Integer。

意图代码:

private void nextPage()
{
    Intent intent = new Intent(this, Timer.class).putExtra("totalTime", totalTime);
    startActivity(intent);
}

定时器中的代码 class:

    Bundle time = getIntent().getExtras();

    if(time == null)
    {
        timeDisp.setText("Failed.");
    }
    else
    {
        totalTimeMs = Integer.parseInt(String.valueOf(time));
        timeDisp.setText(totalTimeMs);
    }

提前致谢:)

如果您的 totalTime 是您通过 putExtra()int 类型,您可以使用:

int time = getIntent().getExtras().getInt("totalTime");

您没有将您的意图添加到 Bundle,因此在接收时 activity 您正在尝试从空 Bundle 中获取数据。

您可以通过以下方式将数据添加到包中:

private void nextPage()
{
    Intent intent = new Intent(this, Timer.class);
    Bundle b = new Bundle():
    b.putString("totalTime", totaltime);

    intent.putExtras(b);
    startActivity(intent);
}

然后您将从包中检索字符串:

Intent intent = getIntent();
Bundle extras = intent.getExtras();

String time = extras.getString("totalTime");

Intent 可以直接包含所有 java 基元类型和 parcelable/serializable 对象。

你可能会有一个困惑,它也可以容纳 Bundle。

您真的需要将整数放入 Bundle 中吗?对于逻辑上耦合的多个值可能是正确的。

检查Intent API