传递的整数值始终会重置为默认值 [英] Value of passed integer always resets back to default value

查看:45
本文介绍了传递的整数值始终会重置为默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Bal 始终重置为0.

Continue = (Button)findViewById(R.id.btnContinue);

Continue.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent startIntent = new Intent(SecondActivity.this, Mainmenu.class);
        int Bal = Integer.parseInt(Balance.getText().toString());
        int MonthlyTarget = Integer.parseInt(Target.getText().toString());
        startIntent.putExtra("intBalance", Bal);
        startIntent.putExtra("intTarget", MonthlyTarget);
        startActivity(startIntent);
    }
});

另一项活动:

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

int MonthlyTarget = startIntent.getIntExtra("intTarget", 0);
Intent RecordExpense = getIntent();
int Expense = RecordExpense.getIntExtra("intExpense", 0);
Intent RecordIncome = getIntent();
int Income = RecordIncome.getIntExtra("intIncome", 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 + "");
}

每当我将 5 用作余额,将 3 用作费用时,我期望输出为 2 .但是实际输出是 -3

Whenever i put 5 as Balance, and 3 as expense, I expected output to be 2. But the actual output is -3

推荐答案

您要在"intBalance"的 Intent 中放入0,而不是将值 Bal 放入

You're putting 0 in the Intent for "intBalance", instead of putting the value Bal.

Continue = (Button)findViewById(R.id.btnContinue);

Continue.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent startIntent = new Intent(SecondActivity.this, Mainmenu.class);
        int Bal = Integer.parseInt(Balance.getText().toString());
        int MonthlyTarget = Integer.parseInt(Target.getText().toString());
        // Change 0 to Bal
        startIntent.putExtra("intBalance", Bal);
        startIntent.putExtra("intTarget", MonthlyTarget);
        startActivity(startIntent);
    }
});

P-S-尝试遵循命名约定,尽管看起来似乎无关紧要,但是当变量名看起来像类名时,很容易错过简单的事情.

P.S - Try to follow naming conventions, although it might seem inconsequential, it's easy to miss simple things when variable names look like class names.

此外,不要不必要地创建诸如 startIntent RecordExpense & RecordExpense . getIntent()已经使您可以访问该意图,您无需每次都获取并将其引用存储在变量中.

Also, don't unnecessarily create variables like startIntent, RecordExpense & RecordExpense. getIntent() already gives you access to the intent, you don't need to get and store a reference to it in a variable everytime.

这篇关于传递的整数值始终会重置为默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆