如何在活动中存储整数以进行计算

时间:2015-02-27 13:08:45

标签: java android android-studio sharedpreferences calculator

我正在创建一个应用程序,它将值组合在一起以提供总体总数,就像这样。 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来增加食物卡路里。

2 个答案:

答案 0 :(得分:1)

在MainActivity中采用静态变量

static int count=0;

获得价值

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

并将其添加到

count+=Integer.parseInt(calorie);

并将值设置为edittext

 textView1.setText(count+"");

希望这会对你有所帮助。

答案 1 :(得分:0)

当您在oldValue= Integer.parseInt(myString);中分配oldValue时,它会使用myString,当我们需要使用strOldValue时,您将在此处String strOldValue = textView1.getText().toString(); 一个问题只是你的疏忽,祝你好运)