错误:java.lang.RuntimeException,如何正确获取intent的额外内容?

时间:2014-09-11 14:51:29

标签: java android android-intent

我正在尝试在两个布局之间设置一个Intent:

searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        long id = listOfDrugs.get(i).getId();
        Intent detailsDrugIntent = new Intent(MainActivity.this, DrugDetails.class);
        detailsDrugIntent.putExtra("id", id);
        startActivity(detailsDrugIntent);
    }
});

以这种方式调用它的附加内容:

id = Long.parseLong(this.getIntent().getStringExtra("id")); // THIS WHERE THE ERROR OCCURS

继续这种方式会触发此错误消息:

  

FATAL EXCEPTION:main java.lang.RuntimeException:无法启动   活动   ComponentInfo {} com.mypharmacy.app/com.mypharmacy.app.DrugDetails:   java.lang.NullPointerException:println需要一条消息

请问如何解决这个问题?

提前致谢!

2 个答案:

答案 0 :(得分:1)

请改为尝试:

id = this.getIntent().getExtras().getLong("id", 1L);

答案 1 :(得分:0)

你可以在其他活动中获得Extras,就像这样

Bundle extras = getIntent().getExtras();
   if (extras != null) 
   {
     long value = extras.getLong("id");
   }