Vahid Amiri
Vahid Amiri

Reputation: 11117

RecyclerView crashes when used in fragment but not in activity

I was using a recyclerview in an activity and now decided to use it in a fragment instead. Now my code crashes at layoutmanager = new LinearLayoutManager (globalContext); with a NullPointerException.

I have no idea why. As I said it worked perfectly fine when used in activity.

I'm using Xamarin but that really doesn't make any difference.

I have only included the first parts of the code as app crashes before reaching others.

private Context globalContext = null;
        RecyclerView recyclerview;
        RecyclerView.LayoutManager layoutmanager;
        NewsAdapter adapter;

        public LatestNewsFragment()
        {
            this.RetainInstance = true;
        }

        public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            var view = inflater.Inflate(Resource.Layout.fragment_latestnews, null);

            // Get our RecyclerView layout:
            recyclerview = view.FindViewById<RecyclerView> (Resource.Id.recyclerView);

            return view;
        }

        public override async void OnActivityCreated(Bundle savedInstanceState)
        {
            base.OnActivityCreated(savedInstanceState);
            globalContext = this.Context;

            //............................................................
            // Layout Manager Setup:

            // Use the built-in linear layout manager:
            layoutmanager = new LinearLayoutManager (globalContext);

            // Plug the layout manager into the RecyclerView:
            recyclerview.SetLayoutManager (layoutmanager);

            //............................................................
            // Adapter Setup:

            // Create an adapter for the RecyclerView, and pass it the
            // data set to manage:

            var rest = new RestAccess();    
            var listofarticles = await rest.ListArticlesAsync("somesource", "1");
            adapter = new NewsAdapter (listofarticles, globalContext);

            // Register the item click handler (below) with the adapter:
            adapter.ItemClick += OnItemClick;

            // Plug the adapter into the RecyclerView:
            recyclerview.SetAdapter (adapter);
        }

        // Handler for the item click event:
        void OnItemClick (object sender, int position)
        {
            // Display a toast that briefly shows the enumeration of the selected photo:
            int photoNum = position + 1;
            Toast.MakeText(globalContext, "This is card number " + photoNum, ToastLength.Short).Show();
        }
    }

Edit:

So I changed the OnCreateView to :

public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    var view = inflater.Inflate(Resource.Layout.fragment_latestnews, null);

    // Get our RecyclerView layout:
    recyclerview = view.FindViewById<RecyclerView> (Resource.Id.recyclerView);

    // Plug the layout manager into the RecyclerView:
    recyclerview.SetLayoutManager (new LinearLayoutManager (Activity));

    return view;
}

And still getting nullpointer exception at recyclerview.SetLayoutManager (new LinearLayoutManager (Activity));

Edit 2:

variable recyclerview is actually null. Don't know why.

Answer: My app was crashing for two reasons:

1- layoutmanager must be defined in OnCreateView but I was doing it in OnActivityCreated.

2- My fragment layout file didn't include the RecyclerView.

Upvotes: 0

Views: 1514

Answers (3)

Htoo Aung Hlaing
Htoo Aung Hlaing

Reputation: 2263

Try with getActivity()

layoutmanager = new LinearLayoutManager (getActivity());

Upvotes: 1

Abdullah Shoaib
Abdullah Shoaib

Reputation: 2095

You need to set LayoutManager in onCreateView() after initializing RecyclerView, instead of setting in onActivityCreated():

mRecyclerView =  (RecyclerView)v.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(newLinearLayoutManager(mRecyclerView.getContext()));   

Upvotes: 2

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132982

Instead of this.Context use getActivity() to get Context in Fragment class. Change:

globalContext = this.Context;

to

globalContext = getActivity();

Upvotes: 1

Related Questions