I have an error on my LinearLayoutManager
, when I run this code its says
error: incompatible types: NotificationFragment cannot be converted to Context
Here is my code NotificationFragment.java
public class NotificationFragment extends Fragment {
private RecyclerView recyclerView;
private NotificationAdapter adapter;
private ArrayList<NotificationModel> notificationModelArrayList;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_notification,container,false);
addData();
recyclerView = (RecyclerView) getView().findViewById(R.id.recycler_view);
adapter = new NotificationAdapter(notificationModelArrayList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(NotificationFragment.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
void addData(){
notificationModelArrayList = new ArrayList<>();
notificationModelArrayList.add(new NotificationModel("Event 1", "1 January 2019", "Surabaya"));
notificationModelArrayList.add(new NotificationModel("Event 2", "1 January 2019", "Surabaya"));
notificationModelArrayList.add(new NotificationModel("Event 3", "1 January 2019", "Surabaya"));
notificationModelArrayList.add(new NotificationModel("Event 4", "1 January 2019", "Surabaya"));
}
}
The error is on
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(NotificationFragment.this);
Hope you can help me, thanks.
You can't cast a Fragment
to a Context
.
Edit this line:
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(NotificationFragment.this);
to:
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
or
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
Remember to check null for getContext()
or getActivity()
before using it.
For your new question from the comment below, just bring the return statement to the end of function:
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_notification,container,false);
addData();
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
adapter = new NotificationAdapter(notificationModelArrayList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(NotificationFragment.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
return view;
}
Use getActivity() instead of NotificationFragment.this
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With