intent.getStringExtra()返回null

时间:2016-04-14 06:08:30

标签: android android-intent

我真的觉得这很奇怪,除了一个,我能够得到其他值。这是我的代码:

Intent intent = new Intent(this.context, SecondActivity.class);
intent.putExtra("contact", n.getContact());
intent.putExtra("email", n.getEmail());
intent.putExtra("address", n.getAddress());
intent.putExtra("test", "hello world");
context.startActivity(intent);

这是我在OnCreate()下获取值的代码:

Intent intent = getIntent();
contact = intent.getStringExtra("contact");
email = intent.getStringExtra("email");
address = intent.getStringExtra("address");
test = intent.getStringExtra("test");

除了字符串test之外,一切正常。它总是会给我null值。对此有何解决方案?

问题补充: intent.putExtra()在第二个参数上是否不再接受引用的文本? LOL

4 个答案:

答案 0 :(得分:0)

在MainActivity.class中

Intent myIntent=new Intent(MainActivity.this, ResultActivity.class);
Bundle bundle=new Bundle();
bundle.putString("contact", n.getContact());
bundle.putString("email", n.getEmail());
bundle.putString("address", n.getAddress());
bundle.putString("test", "hello world");
myIntent.putExtra("MyPackage", bundle);
startActivity(myIntent);

在ResultActivity.class中

Intent callerIntent=getIntent();
Bundle packageFromCaller=
callerIntent.getBundleExtra("MyPackage");
String contact =packageFromCaller.getString("contact");
String email =packageFromCaller.getString("email");
String address= packageFromCaller.getString("address");
String test= packageFromCaller.getString("test");

希望。它会帮助你!!!

答案 1 :(得分:0)

使用 getApplicationContext()代替 this.context 并使用 startActivity 代替 context.startActivity

第一项活动

Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("test", "hello world");
startActivity(intent);

第二项活动

Intent intent = getIntent();
intent.getStringExtra("test");

答案 2 :(得分:0)

您需要在每个 putExtra 上添加 .toString() 和方法调用的结尾

Intent intent = new Intent(this.context, SecondActivity.class);
intent.putExtra("contact", n.getContact().toString());
intent.putExtra("email", n.getEmail().toString());
intent.putExtra("address", n.getAddress().toString());
intent.putExtra("test", "hello world");
context.startActivity(intent);

答案 3 :(得分:-1)

发送数据

Intent intent  = new Intent(this.context,SecondActivity.class);
                intent.putExtra("contact", n.getContact());
                startActivity(intent);

获取数据

Bundle data = getIntent().getExtras();
contact = data.getString("contact");