【问题标题】:Importing data from another activity, Android studio从另一个活动导入数据,Android Studio
【发布时间】:2023-04-02 06:46:01
【问题描述】:

这是我的主要课程。我从用户输入中收到双打。

public void onPayClick(View view){
    Intent payIntent = new Intent(this, payActivity.class);

    final EditText amountInput = (EditText) findViewById(R.id.amountInput);
    final EditText yearInput = (EditText) findViewById(R.id.yearInput);
    final EditText interestInput = (EditText) findViewById(R.id.interestInput);

    double amountDouble = Double.parseDouble(amountInput.getText().toString());
    double yearDouble = Double.parseDouble(yearInput.getText().toString());
    double interestDouble = Double.parseDouble(interestInput.getText().toString());

    payIntent.putExtra("amountDouble", amountDouble);
    payIntent.putExtra("yearDouble", yearDouble);
    payIntent.putExtra("interestDouble", interestDouble);

    startActivity(payIntent);
}

这是我的第二个活动,在这里我想计算贷款,但我只是想打印 amountDouble 以查看它是否有效,但它没有......

TextView printPay = (TextView) findViewById(R.id.printPay);


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pay);

    Bundle payData = getIntent().getExtras();

    if(payData == null){
        printPay.setText("Villa, þú verður að filla upp í alla reiti.");
        return;
    }
    String amountDouble = payData.getString("amountDouble");
    String yearDouble = payData.getString("yearDouble");
    String interestDouble = payData.getString("interestDouble");

    String sum1 = amountDouble;
    printPay.setText(sum1);
}

每次我点击 payButton 时,应用程序都会崩溃。

【问题讨论】:

  • 您在第二个活动中定义 TextView printPay 的位置?
  • 您必须在 onCreate 中的 setContentView 之后执行此操作。
  • TextView printPay = (TextView) findViewById(R.id.printPay); 定义在onCreate()

标签: java android android-intent android-activity input


【解决方案1】:

从第一个Activity 开始,您将这些值直接添加到intent 中,因此您必须从intent 而不是从bundle 获取这些数据。除此之外,您在类的顶部声明TextView,因此在setContentView(R.layout.activity_pay); 之后在onCreate(...) 中定义它将是null。在第二个Activity 改成这样

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pay);
    TextView printPay = (TextView) findViewById(R.id.printPay);

    String amountDouble = String.valueOf(getIntent().getDoubleExtra("amountDouble", 0.0));
    String yearDouble = String.valueOf(getIntent().getDoubleExtra("yearDouble", 0.0);
    String interestDouble = String.valueOf(getIntent().getDoubleExtra("interestDouble", 0.0);

    String sum1 = amountDouble;
    printPay.setText(sum1);
}

more info of getDoubleExtra(java.lang.String, double)

【讨论】:

  • 问题出在 TextView 上。非常感谢!
猜你喜欢
  • 2019-08-20
  • 2022-01-25
  • 2013-10-04
  • 1970-01-01
  • 1970-01-01
  • 2020-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多