Create the adapter and the "non-view" related objects in onCreate
. Then use your adapter for the RecyclerView
.
Also, clean up your code by initiating the objects in a clear order based on their use and the Activity
lifecycle.
public class StatsFragment extends Fragment {
private RecyclerView mRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private StatsAdapter mAdapter; // was RecyclerView.Adapter mAdapter;
private String[] myDataset = new String[]{"hello", "world", "yolo"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 1.
mAdapter = new StatsAdapter(myDataset);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_stats, parent, false);
// 2.
mLinearLayoutManager = new LinearLayoutManager(getActivity());
mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
// 3.
mRecyclerView = (RecyclerView) v.findViewById(R.id.cardList);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setAdapter(mAdapter);
return v;
}
}