【问题标题】:Convert Bundle to Integer (Intents)将捆绑包转换为整数(意图)
【发布时间】:2016-04-14 14:40:03
【问题描述】:

我试图通过一个意图将一个 int 传递给另一个类,并成功地传递了整数,但是我不确定如何将一个 Bundle 转换为一个整数。

意图代码:

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

Timer 类中的代码:

    Bundle time = getIntent().getExtras();

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

提前致谢:)

【问题讨论】:

    标签: java android android-intent bundle


    【解决方案1】:

    Intent 可以直接保存所有 Java 基元类型和可打包/可序列化的对象。

    您可能对它也可以容纳 Bundles 感到困惑。

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

    检查Intent API

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        您没有将意图添加到 Bundle,因此在接收活动中,您正试图从空的 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");
        

        【讨论】:

        • 实际上 new intent(...).putExtra("tag", value) 是有效的,并将数据添加到意图包中
        猜你喜欢
        • 1970-01-01
        • 2012-11-21
        • 2011-01-11
        • 2020-01-04
        • 1970-01-01
        • 2021-06-22
        • 2021-07-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多