在viewpager报告中刷新嵌套片段nullpointerexception

时间:2015-11-04 02:43:34

标签: nullpointerexception fragment refresh

这是我的项目构造,如下所示: this is my project's construct

Fragment1 hava一个viewpager来嵌套两个子片段:A和B,Fragment2,3,4都是这样的。然后Fragment A和B都用hava refreshData()方法来刷新data.Now Fragment1 hava一个按钮来选择城市。我想在改变城市后刷新片段A和B.

 但是当我从Fragment1切换到Fragment4,然后切换回Fragment1并单击按钮更改城市,当调用refreshData()时,getActivity()方法返回null,因此将显示NullPointerException错误。

让我发疯.FragmentA和FragmentB都在onCreateView上执行,为什么getActivity()返回null?

片段代码:

public class Fragment1 extends Fragment {


public Fragment1() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_fragment1, container, false);
}



public void refreshData(String city){

    if ( null != getActivity()){

        //get data from webservice
    }

}


}

Fragment1.java:

    private List<Fragmnet> mFragmentList;
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    mFragmentList = new ArrayList<>();
    mFragmentList.add(new FragmentA());
    mFragmentList.add(new FragmentB());
    View v =inflater.inflate(R.layout.fragment_creadit, container, false);

    viewPager = (ViewPager) v.findViewById(R.id.pager);

    adapter = new ViewPagerAdapter(getResources(),  getChildFragmentManager(),titleList,mFragmentList);


    viewPager.setAdapter(adapter);


    return v;



}
  

更新:我知道为什么getActivity()返回null。这是因为Fragment1将显示旧的fragmentA和FragmentB,即使你重新执行Fragment1的onCreateView()来添加新的FragmentA \ b并更改fragmentAdapter的数据。   
  所以我将Fragment1的onCreateView()改为:

List<Fragmnet> mFragmentList ;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {



    if(  null ==  mFragmentList){
    mFragmentList  = new ArrayList<>();
    mFragmentList.add(new FragmentA());
    mFragmentList.add(new FragmentB());
    }

    View v =inflater.inflate(R.layout.fragment_creadit, container, false);

    viewPager = (ViewPager) v.findViewById(R.id.pager);

    adapter = new ViewPagerAdapter(getResources(),  getChildFragmentManager(),titleList,mFragmentList);


    viewPager.setAdapter(adapter);


    return v;



}

所以当我调用refreshData()时,这是旧的FragmentA的refreshData(),而不是新的FragmentA。

0 个答案:

没有答案