I have implemented a list fragment inside my main activity. I open fragment by this code:
fragmentTransactionChat = getSupportFragmentManager().beginTransaction();
if(savedInstanceState == null) {
itemFragment = ChatItemFragment.newInstance(1);
fragmentTransactionChat.add(R.id.frame_main, itemFragment, "chatFragment").commit();
}
else {
itemFragment = (ChatItemFragment) getSupportFragmentManager().findFragmentByTag("chatFragment");
}
and this is onCreateView
method in fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
View view = inflater.inflate(R.layout.fragment_item_list, container, false);
// Set the adapter
final Context context = view.getContext();
recyclerView = (RecyclerView) view.findViewById(R.id.list);
if (mColumnCount <= 1) {
linearLayoutManager = new PreCachingLayoutManager(context);
recyclerView.setLayoutManager(linearLayoutManager);
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
mAdapter = new PostRecyclerViewAdapter(getActivity(), mListener);
recyclerView.setAdapter(mAdapter);
RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
if (animator instanceof SimpleItemAnimator) {
((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
}
recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager, mAdapter) {
@Override
public void onBottomList() {
floatingActionButton.hide();
}
});
postProvider = PostProvider.getInstance(getActivity());
postProvider.setCallListener(this);
bindItems(view);
if(savedInstanceState == null) {
postProvider.loadPost();
}
bindNotificationManager();
return view;
}
My problem is when I rotate the device, onCreateView
method is called again and mAdapter object and others are null, so it causes problem in my logic.
Note: My fragment isn't added by my main activity after rotation, because I have handled it by this condition command:
if(savedInstanceState == null)
What's the problem?!