android开发 -- 利用intent来传递int数据

在android系统中的intent对象是不支持直接传递int数据类型的;

如果直接传int值会报错,提示如 :Key ID expected Integer but value was a java.lang.Long.  The default value -1 was returned.

那么解决这类问题有两种方法:

方法一:
通过数据类型转换,不过在有些特殊的情况下这种方法并不适用
例如发送端:
int id=10;

Intent intent = new Intent(this, EditActivity.class);
intent.putExtra("id", id+"");      // id+"" 这样是把int转成String类型, 否则会报错
startActivity(intent);
接收端:
String sID=getIntent().getStringExtra("id");
int id=Integer.parseInt(sID);      //String转int


方法二:
通过bundle这个对象来封装数据进行传递,
例如发送端:
Bundle bundle = new Bundle();
bundle.putInt("id", 3);
intent.putExtras(bundle);
这样就可以解决问题。

你可能感兴趣的:(Android开发)