Reputation: 481
I'm trying to pass an integer value from an activity to another one.
In the second activity I want to convert my string to an integer to do some calculations and convert it again to a string for showing it in a TextView.
This is my first activity:
public class GetPrice extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.getprice);
final EditText et1 = (EditText) findViewById(R.id.getprice);
Button getb1 = (Button) findViewById(R.id.getbutton);
getb1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i1 = new Intent(GetPrice.this, Price1.class);
int fl1 = Integer.parseInt(et1.getText().toString());
i1.putExtra("theprice", fl1);
startActivity(i1);
}
});
And this is my second activity:
public class Price1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.price1);
String st1 = new String(getIntent().getExtras().getString("theprice"));
Integer int1 = Integer.valueOf(st1);
//some calculation with int1
TextView tv1 = (TextView) findViewById(R.id.price1text);
tv1.setText(String.valueOf(int1));
}
But, when I press the "getbutton", the application crashes.
what is the problem?
Thanks
Upvotes: 0
Views: 133
Reputation: 31597
Use Bundle.getInt(String key)
for accessing int fl1
putted in GetPrice
class.
Integer int1 = getIntent().getExtras().getInt("theprice");
Updated to older JDK.
Also you dont need to reconvert values from type to type like this:
String st1 = new String(getString...);
Integer int1 = Integer.valueOf(st1);
tv1.setText(String.valueOf(int1));
The should be simplified to code like this
String st1 = Integer.toString(getString...);
tv1.setText(st1);
or even better
Integer int1 = getInt...;
tv1.setText(String.valueOf(int1));
Upvotes: 1
Reputation: 76908
Without the stacktrace and the actual error, either
int fl1 = Integer.parseInt(et1.getText().toString());
is the problem, and the String
isn't a textual representation of an integer, or that's actually working and this:
String st1 = new String(getIntent().getExtras().getString("theprice"));
is the problem because you stored an Integer
in extras and are now trying to get it as a String
(use getInt("theprice")
instead).
Upvotes: 3