【问题标题】:How to store an integer in an activity for calculation如何将整数存储在活动中以进行计算
【发布时间】:2015-02-27 13:08:45
【问题描述】:

我目前正在创建一个应用程序,该应用程序将值相加以得出总体总数,就像这样。 oldValue + newValue = textView1...

MainActivity,这是在 textView1 中存储整体值的地方

 String calorie = getIntent().getStringExtra("calorie");
        TextView textView1 = (TextView)findViewById(R.id.textView1);
        String strOldValue = textView1.getText().toString();

        Integer oldValue;
        try{
            oldValue= Integer.parseInt(myString);
        }catch(NumberFormatException e){
            oldValue =0;
        }

        Integer newValue;
        try{
            newValue= Integer.parseInt(calorie);
        }catch(NumberFormatException e){
            newValue =0;
        }
        textView1.setText((oldValue + newValue));

问题是 textview 忘记了旧值而只是插入新值...所以携带 100,然后我去添加 150...我只看到 150。相信我需要存储100(oldValue)某处。有什么建议吗?

上下文:这是一个食物计算器,它使用 AddActivity 和 MainActivity 添加食物卡路里。

【问题讨论】:

  • 这里的 myString 是什么?
  • 代码 sn-p 未显示 myString 的值来自何处。
  • 从我的 AddActivity 类中携带的一个字符串,包含 newValue。

标签: java android android-studio sharedpreferences calculator


【解决方案1】:

在 MainActivity 中取一个静态变量

static int count=0;

并获得价值

String calorie = getIntent().getStringExtra("calorie");

并将其添加到

count+=Integer.parseInt(calorie);

并将值设置为edittext

 textView1.setText(count+"");

希望对你有帮助。

【讨论】:

    【解决方案2】:

    当您在 oldValue= Integer.parseInt(myString); 中分配 oldValue 时,它​​使用 myString,当我们需要使用 strOldValue 时,您可以在这里找到 String strOldValue = textView1.getText().toString(); 问题只是你的不注意,祝你好运)

    【讨论】:

    • 是的,虽然它仍然没有添加两个值。
    猜你喜欢
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    相关资源
    最近更新 更多