Kyle Mutta
Kyle Mutta

Reputation: 409

How to add items in a recycler view from a different class

Have implemented a recycler view found on my notification fragments on adding itesm on the same fragments no problem occurs but when i try to add items from another fragment it throws and eror JavaNullPointException.

here is my fragment that has the recycler view

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View v = inflater.inflate (R.layout.fragment_notificationcict, container, false);






        notimodels = new ArrayList<> ();

        mRecyclerView = v.findViewById(R.id.notificationsRecycler);


        fillNotification (R.drawable.logo, "OCApp", "Welcome to Online Clearance Application,Get cleared now , avoid queing up in offices , save time and money.",+ minutes+"min");

        // get data from the notificiation
        return  v;
    }




    @Override
    public void onStart() {
        super.onStart ();
        swipeRefreshLayout.setRefreshing(true);
        fillNotification (R.drawable.logo, "OCApp", "Welcome to Online Clearance Application,Get cleared now , avoid queing up in offices , save time and money.",+ minutes+"min");
    }



   public void fillNotification(int mImage, String mtext, String mtext2, String mDate)
    {
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager (getContext ());
        mAdapter = new NotificationAdapter (notimodels);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        notimodels.add (0,new NotificationModel (mImage,mtext,mtext2,mDate));
    }
}

**When i try to call the function from other fragments like tis forexample""

NotificationFragmentCict notificationFragmentCict =new NotificationFragmentCict ();
        notificationFragmentCict.fillNotification (R.drawable.bursar, "Bursar", "your clreard","min");

My App crushes and throws this error

Process: com.univibezstudios.ocappservice.ocapp, PID: 3380
    java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference

The problem is this one This error is showing because your fragment's view is not created yet. That's why recyclerview is null and you're invoking setHasFixedSize(...) method on you null recyclerview. but icant solve it any help guys

Upvotes: 1

Views: 60

Answers (1)

Sharone Lev
Sharone Lev

Reputation: 841

You need to initialize the recycler view which you left out of the function fillNotification:

mRecyclerView = v.findViewById(R.id.notificationsRecycler);

you also need the ArrayList in the second fragment:

  notimodels = new ArrayList<> ();

Upvotes: 1

Related Questions