如何将对象从一个片段传递到另一个片段?

时间:2017-01-19 12:19:10

标签: android android-fragments nullpointerexception

片段代码MoneyTransferFragment ......

MoneyTransferFragment moneyTransferFragment = new MoneyTransferFragment();
                    Bundle b = new Bundle();
                    b.putSerializable("UserValidateObject",userValidate);
                    b.putSerializable("BeneficiaryObject",beneficiaryDetails);
                    moneyTransferFragment.setArguments(b);

第二个片段的代码,我想要检索该对象.......

Bundle b = getArguments();
    userValidate =(UserValidate) b.getSerializable("UserValidateObject");
    Log.i("getuserValidate",userValidate.toString());

在日志中显示错误..........

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

1 个答案:

答案 0 :(得分:4)

更改您的代码 发件人:

Bundle b = getArguments();
userValidate =(UserValidate) b.getSerializable("UserValidateObject");
Log.i("getuserValidate",userValidate.toString());

userValidate=(UserValidate)getArguments().getSerializable("UserValidateObject");
Log.i("getuserValidate",userValidate.toString());

活动有效:

    (YourObject)getIntent().getSerializableExtra("keyname");

片段作品:

 (YourObject)getArguments().getSerializable("keyname");