当从intent传递到目标活动时,android extra arg为null

时间:2014-01-02 11:24:26

标签: android

在TrainingDetailFragment中,我需要启动一个SwimlogListActivity来显示与Training详细信息相关的所有swimlog的列表。

所以在我的TrainingDetailFragment中,我编写了一个Intent并将training_id作为额外的函数传递(调试器日志:mItem.id:2)

public class TrainingDetailFragment extends Fragment {
    ....
    Intent swimlogs = new Intent(getActivity(), SwimlogListActivity.class);
    swimlogs.putExtra("trainingID", mItem.id);
    startActivity(swimlogs);

在SwimlogListActivity中,我测试我是否可以获得trainingID arg ..

 public class SwimlogListActivity extends FragmentActivity implements SwimlogListFragment.Callbacks {

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_swimlog_list);

    Intent intent = getIntent();
    if(intent != null) {
        String trainingID = intent.getStringExtra("trainingID");
        Log.i(TAG, "SwinglogListActivity - onCreate() with trainingID: "  + trainingID);
    }

但我得到一个trainingID null ..... SwinglogListActivity - onCreate()with trainingID:null

我哪里可能出错? btw Happy 2014 !!

3 个答案:

答案 0 :(得分:0)

几乎可以肯定mItem.id不是String,如果它是int,例如,使用intent.getIntExtra

获取它

答案 1 :(得分:0)

   Bundle extras = getIntent().getExtras();
     if (extras != null) {
     String datas= extras.getString("EXTRA_ID");
     if (datas!= null) {
       // do stuff
    }        
 }

了解更多信息:link

答案 2 :(得分:0)

认为您的mItem.id是整数,因此您只需将SwimlogListActivity的代码替换为:

...
Intent mIntent = getIntent();
if(mIntent != null) {
    int trainingID = mIntent.getIntExtra("trainingID", 0);
    Log.i(TAG, "SwinglogListActivity - onCreate() with trainingID: "  + trainingID);
}