android- nullpointer用于将bundle发送到fragment

时间:2016-09-28 09:38:02

标签: android android-fragments

我是一个自定义的viewpager,我用它在我的应用程序中制作标签。这是我的代码;

    private TabLayout tabLayout;
    private ViewPager viewPager;
private void setupViewPager(ViewPager viewPager) {
        Fragment_Mashaghel fragmnetMashaghel=new Fragment_Mashaghel();

    Bundle bundle = new Bundle();
    Fragment_Cars stock=new Fragment_Cars();
    bundle.putString("type","stock");
    stock.setArguments(bundle);



    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(fragmnetMashaghel, getString(R.string.mashagahel));
    adapter.addFragment(stock, getString(R.string.stock));

    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

这是我的片段:

public class Fragment_Cars extends Fragment {
View v;

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
Bundle b = getActivity().getIntent().getExtras();
    forWhat=b.getString("type");

我在这一行得到空指针异常:

b.getString("type");

有什么问题?如何填充我的包并将我的参数设置为片段?

2 个答案:

答案 0 :(得分:1)

您必须使用getArguments()而非活动意图的额外内容。

Bundle b = getArguments();

完整代码

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Bundle b = getArguments();
    forWhat = b.getString("type");
}

文档:https://developer.android.com/reference/android/app/Fragment.html#getArguments()

答案 1 :(得分:0)

在您的片段类中,使用getArguments()代替getExtras()。例如,您可以尝试以下操作:

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    String forWhat = getArguments().getString("type");
}

希望这有帮助。