Nevid
Nevid

Reputation: 55

RecyclerView Adapter inside Fragment

I set a recycler adapter in fragment inside firebase OnCompleteListener. So, the problem is when I am navigating between fragments quickly (by Navigation View), I have an error "java.lang.IllegalStateException: Fragment not attached to Activity". Android studio gives me the link to that line of my code:

recyclerView.setAdapter(new AdapterRV(requireActivity(), listLeft, listRight));

As I understand the main issue is

requireActivity()

I found some solutions as:

view.getContext()

requireContext()

What is the right one for my case? Or may be there is some better way to fix this?

Upvotes: 0

Views: 371

Answers (1)

Ali Moghadam
Ali Moghadam

Reputation: 1126

In your scenario app throws an exception because of once data arrives and we intent to pass them to the recyclerview, your fragment will be disattached and it causes an exception

and in my opinion the solution would be something like this...

Better Way :

You should add a method to your adapter for pass data:

in OnViewCreated :

adapter = new AdapterRV(requireActivity())

when data received

adapter.submitList(listLeft, listRight)

Another Way :

if you have to set adapter after arrive the data, you need to call adapter after checking if the context is not null

if ( getContext() != null ) 
{
recyclerView.setAdapter(new AdapterRV(requireActivity(), listLeft, listRight));
}

Upvotes: 1

Related Questions