在将对象从一个片段传递到另一个android时获取Null指针异常?

时间:2018-01-21 13:26:17

标签: android android-fragments fragment

我将一个对象从一个片段传递到另一个片段,但是对象在接收时变为null。

发送代码

   Bundle bundle = new Bundle(); 
CustomerInformationFragment fragment = new CustomerInformationFragment(); 
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction(); 
bundle.putSerializable("Object", customer); 
Log.d("Kapil", "setData: " + customer.getClass().getSimpleName()); 
ft.commit(); 
fragment.setArguments(bundle); 

收到代码

    Bundle bundle = new Bundle(); 
Customer = (Customer) getArguments() .getSerializable("Object"); 
Log.d("Kapil", "onCreateView: " + customer.getFirstName()); 

我收到错误

java.lang.NullPointerException: 
Attempt to invoke virtual method 'java.io.Serializable android.os.Bundle.getSerializable(java.lang.String)' 
on a null object reference at 
com.whattebiryani.Fragments.CustomerAddressFragment.onCreateView(CustomerAddressFragment.java:44) 
    at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354) 
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419) 
    at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740) 
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809) 
    at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799) 
    at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580) 
    at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367) 
    at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322) 
    at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2199) 
    at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:651) 
    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:145)

2 个答案:

答案 0 :(得分:0)

首先,您必须为您的片段设置参数,然后您必须提交事务:

fragment.setArguments(bundle);
ft.commit(); 

答案 1 :(得分:0)

在提交事务之前设置参数。

fragment.setArguments(bundle);
ft.commit();