我正在尝试将整数值从一个 Activity 传递到另一个 Activity 。
在第二个 Activity 中,我想将字符串转换为整数以进行一些计算,然后再次将其转换为字符串以在 TextView 中显示。
这是我的第一个 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);
}
});
这是我的第二项 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));
}
但是,当我按下“getbutton”时,应用程序崩溃了。
问题是什么?
谢谢
最佳答案
没有堆栈跟踪和实际错误,要么
int fl1 = Integer.parseInt(et1.getText().toString());
是问题所在,String
不是整数的文本表示,或者它实际上正在工作,并且:
String st1 = new String(getIntent().getExtras().getString("theprice"));
是问题所在,因为您存储了 Integer
在额外的内容中,现在正试图将其作为String
(使用 getInt("theprice")
代替)。
关于java - 如何传递一个类型的值并将其转换为另一种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20938225/