从另一个活动Android Studio导入数据

时间:2015-01-19 09:57:58

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

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

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时,应用程序都会崩溃。

1 个答案:

答案 0 :(得分:3)

从第1 Activity开始,您可以直接在intent添加这些值,因此您必须从intent而不是bundle获取这些数据。除此之外,您在类的顶部声明TextView,因此它将 null onCreate(...)之后在setContentView(R.layout.activity_pay);内定义它。在第二次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)