【问题标题】:How to pass an integer from one activity to another in android application [duplicate]如何在android应用程序中将整数从一个活动传递到另一个活动[重复]
【发布时间】:2020-11-09 22:51:48
【问题描述】:

我正在尝试学习 android,但我不知道如何将数据从一个活动传递到另一个活动

 public void onNextClick(View view){
    Intent intent = new Intent(this,Expenses.class);
    intent.putExtra(EXTRA_SUM, sum);
    startActivity(intent);

    editSalary = (EditText) findViewById(R.id.salayText);
    editIncome = (EditText) findViewById(R.id.incomeText);
    salary = Integer.parseInt(editSalary.getText().toString());
    income = Integer.parseInt(editIncome.getText().toString());
    sum = salary + income;
}


    public void onNextClick2(View view){
    Intent intent2 = new Intent(Expenses.this,Budget.class);
    intent2.putExtra(EXTRA_EXPENSE, expense);
    startActivity(intent2);

    editRent = (EditText) findViewById(R.id.rentText);
    editBills = (EditText) findViewById(R.id.billsText);
    editEveryday = (EditText) findViewById(R.id.everydayText);
    editOther = (EditText) findViewById(R.id.otherText);
    rent = Integer.parseInt(editRent.getText().toString());
    bills = Integer.parseInt(editRent.getText().toString());
    everyday = Integer.parseInt(editEveryday.getText().toString());
    other = Integer.parseInt(editOther.getText().toString());
    expense = rent + bills + everyday + other;
}


    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_budget);

    Intent intent = getIntent();
    summary =  intent.getIntExtra(MainActivity.EXTRA_SUM ,0);
    expenses = intent.getIntExtra(Expenses.EXTRA_EXPENSE, 0);
    totalBudget = summary - expenses;
    textBudget = (TextView) findViewById(R.id.budgetView);
    textBudget.setText(String.valueOf(totalBudget));
}

我试图从活动 1 中获取“总和”,从活动 2 中获取“费用”,然后在活动 3 中减去它们,但我一直为空

【问题讨论】:

标签: java android android-activity


【解决方案1】:

您不能将值从第一个活动直接传递到第三个活动。首先您必须将其传递给first-> second,然后再传递给second-> third

还有一个简单的解决方案,例如您可以将其存储在 Shared Preferences 从第一个活动移动到第二个活动时,将总和值存储在共享偏好上。然后当您从第二个活动移动到第三个活动时,将费用值存储在共享偏好上。之后,在第三个活动的onCreate 方法中,您可以获得两个值并减去.

【讨论】:

    【解决方案2】:

    有很多方法可以做到这一点。

    1. 查看模型
    2. 单例
    3. 在启动新活动的 Intent 中传递它

    【讨论】:

      猜你喜欢
      • 2011-10-27
      • 1970-01-01
      • 2018-05-31
      • 2016-07-24
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多