0

Activity

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    Bundle bundlee;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ........
        }

    private void setupViewPager(ViewPager viewPager) {

        ViewPagerAdapter adapter = new 

ViewPagerAdapter(getSupportFragmentManager());

        final int[] arrayTitle = new int[bundle];

        for (int i = 0; i < 5; i++)
        {
            arrayTitle[i]=i;
        }
        bundlee= new Bundle();
        bundlee.putIntArray("arrayTitlee", arrayTitle);
        TwoFragment TwoFragment = new TwoFragment();
        TwoFragment.setArguments(bundlee);

        adapter.addFragment(new OneFragment(), "....");

        adapter.addFragment(TwoFragment, "....");
        adapter.addFragment(new ThreeFragment(),".....");
        viewPager.setAdapter(adapter);
    }

    private 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);
        }
    }
}

Fragment 2

public class TwoFragment  extends Fragment {

    public TwoFragment() {

    }
    int arrayTitle[]=new int[0];
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_two, container, false);
       arrayTitle=getActivity().getIntent().getExtras().getIntArray("arrayTitle");


        mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);


        mRecyclerView.setHasFixedSize(true);

        mLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(mLayoutManager);
        dataModels = new ArrayList<>();
        for (int i = 0; i < bundle; i++)
        {
        arrayTitle[i]=i;
            dataModels.add(new ...(String.valueOf(arrayTitle[i]), i, i, i, i));
        }
        adapter = new ..(dataModels, getContext());
        mRecyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        return view;
    }
}

Error

java.lang.NullPointerException: Attempt to write to null array                                                                        at com.example.TwoFragment.onCreateView(TwoFragment.java:61)

 for (int i = 0; i < bundle; i++)
    {
    arrayTitle[i]=i;//вот здесь показывает ошибку 
        dataModels.add(new ......(String.valueOf(arrayTitle[i]), i, i, i, i));
    }
1

1 ответ 1

0

Вы создали фрагмент и положили туда аргументы

OneFragment fragment = new OneFragment();
fragment.setArguments(bundlee);

Но потом не отобразили его. А там, где вы его отображаете вы аргументы в него не кладёте. Вот они и null

11
  • @fcbarcafc, добавьте в вопрос то место в коде, где вы на самом деле фрагмент добавляете на экран. Именно там и надо массив в аргументы класть.
    – ЮрийСПб
    10 дек 2017 в 18:53
  • @fcbarcafc, собственно вот где вы фрагмент создаёте, а его потом ViewPager отображает: adapter.addFragment(new TwoFragment(), "Fragment 2"); Вот там и создавайте аргументы и передавайте их во фрагмент. А в первом фрагменте вы это делаете впустую.
    – ЮрийСПб
    10 дек 2017 в 20:42
  • Fragment twoFragment = new TwoFragment(); //тут аргументы etc adapter.addFragment(twoFragment, "Fragment 2");
    – ЮрийСПб
    10 дек 2017 в 21:52
  • @fcbarcafc, кода слишком много. Решите, в чём именно ваш вопрос. Сейчас он уже не про передачу данных во фрагмент, но в том, как инициализировать массив. До сих пор не яссно на какой строке у вас падает. Удалите всё лишнее из проекта. Оставьте только одну активит и один фрагмент. Попытайтесь в него массив передать. Только после этого попытайтесь создать адаптер где будет этот один фрагмент. Потом двигайтесь дальше.
    – ЮрийСПб
    10 дек 2017 в 22:21
  • вопрос все тот же. А инициализирую массив я вот так final int[] arrayTitle = new int[bundle];,разве не правильно?
    – fcbarcafc
    10 дек 2017 в 22:27

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.