hjaltist
hjaltist

Reputation: 59

Importing data from another activity, Android studio

This is my main class. Where I receive doubles from users 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);
}

This is my second activity, here I would like to calculate the loan but I'm just trying to print amountDouble to see if it works, which it doesn't....

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);
}

Each time I click payButton the application crashes.

Upvotes: 0

Views: 3240

Answers (1)

Kaushik
Kaushik

Reputation: 6162

From 1st Activity you are adding those values in intent directly so you have to fetch those data from intent not from bundle. Besides that you are declaring that TextView at the top of your class so it will be null define it inside onCreate(...) after setContentView(R.layout.activity_pay);. In 2nd Activity change like this

@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)

Upvotes: 3

Related Questions