This question already has an answer here:
Value of passed integer always resets back to default value

(1个答案)


在11个月前关闭。





该程序旨在存储余额,并在我输入新收入时增加价值,并在我输入新费用时减少价值。但是,当我输入费用时,余额的值将变为负数,就好像每次开始费用活动时整数Bal都会重置为0一样。

    //Buttons
    btnExpense = (Button)findViewById(R.id.btnExpense);
    btnExpense.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent expenseIntent = new Intent(Mainmenu.this, expenses.class);
            startActivity(expenseIntent);
        }
    });

    btnIncome = (Button)findViewById(R.id.btnIncome);
    btnIncome.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent incomeIntent = new Intent(Mainmenu.this, Income.class);
            startActivity(incomeIntent);
        }
    });



    Intent startIntent = getIntent();
    Intent RecordExpense = getIntent();
    int Expense = RecordExpense.getIntExtra("intExpense", 0);
    Intent RecordIncome = getIntent();
    int Income = RecordIncome.getIntExtra("intIncome", 0);

    int Bal = startIntent.getIntExtra("intBalance", 0);


        TextView tvResult=(TextView) findViewById(R.id.tvResult);
        tvResult.setText(Bal +"");
        if(getIntent().hasExtra("intIncome")) {
            Bal=Bal+Income;

            tvResult.setText(Bal + "");
        }
        if(getIntent().hasExtra("intExpense")) {

            Bal=Bal-Expense;
            tvResult.setText(Bal + "");
        }


每当我输入10作为Bal和5作为费用时,我希望显示5,但改为显示-5

最佳答案

看来您的“ Bal”是从“ startIntent”获取的局部变量。更新后,您无需将“ Bal”重新设置为“ startIntent”。因此,在“ startIntent”中,其值始终为0。每个收支操作均在0上执行。

您需要在Intent类中定义一个方法来更新“ intBalance”中的余额。 startIntent.setIntExtra(“ intBalance”,Bal);

10-07 20:45