将对象从一个片段传递到另一个片段,并将接收到的对象存储在Global对象中

时间:2019-06-09 07:50:58

标签: android interface

我想使用接口(两个片段都在同一活动中)从Fragment1到Fragment2传递模型对象。 我在Fragment2的公共类中收到了该对象。现在,我想将接收到的对象另存为Fragment2的Global变量。这样我就可以使用相同Fragment2的其他方法。 但是...但是... 当我尝试在onCreateView()中使用全局对象时, 得到NULL POINTER EXCEPTION。

In Fragment1, 
 1. Interface declaration 
interface CommunicatePricePlanCheckOutInterface {
        void sendDataToCheckout( SinglePricePlanModel singleModel );
    }
 2. Object of Interface
    CommunicatePricePlanCheckOutInterface  communicationObject;
 3. passing data using method of interface in, onCreateView()
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_price_plan, 
                     container,false);
        allSampleData = new ArrayList<>();
        mPricePlanContinueButton.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) { 
               if (getActivity() != null) {
                  communicationObject.sendDataToCheckout(
                  allSampleData.get(0));
               } 
            }
        }); 
        return view;
       }
In activity, 
 4. implementing the interface
       public class NavDrawerActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, 
         Fragment1.CommunicatePricePlanCheckOutInterface
 5. overriding interface method and in the method calling a public method of Fragment2. 
 @Override
    public void sendDataToCheckout(SinglePricePlanModel pricePlanModel ) {
        Fragment2 frag2 = new Fragment2();
        frag2.receivePlanData(pricePlanModel, mUserBasicInfo);

    }
In Fragment2, 
 6. Received 2 objects from Activity, I can use them in this method, but can not access those mSinglePricePlanModel, mUserBasicInfo objects outside this method, like onCreateView or onViewCreated. Getting Null Pointer Exception if I try to 
access.

public void receivePlanData(SinglePricePlanModel mSinglePricePlanModel , UserBasicInfo mUserBasicInfo ){ 
        this.mSinglePricePlanModel = mSinglePricePlanModel;
        this.mUserBasicInfo = mUserBasicInfo;
}

1 个答案:

答案 0 :(得分:0)

您是否初始化了接口对象?我在您的片段中看不到任何初始化,这可能导致空指针异常。像这样在片段中的onAttach方法中初始化它-

@Override
public void onAttach(Context context) {

    super.onAttach(context);

    if (context instanceof CommunicatePricePlanCheckOutInterface) {

        communicationObject = (CommunicatePricePlanCheckOutInterface) context;
    }
}

那么它不应该给空指针异常。有关更多详细信息,请参阅此link