recycler view null point exception in fragment - android

I have a recyclerview in fragment. When I run the app i get the following message.
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
I have searched and found people with similar problems, but it hasn't helped me. The recyclerview is null in the fragment. Here is my code:
I call the fragment from the main activity here on the onCreate:
FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
trans.add(R.id.recycle_view_container, recyclerViewFragment, RECYCLER_FRAGMENT);
trans.commit();
trans.show(recyclerViewFragment);
Here is my recyclerfragment:
public class RecyclerViewFragment extends Fragment
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
static SQLiteDatabase db;
ArrayList<MyMarker> markerArrayList;
private MyAdapter adapter;
private String TAG = "recyclerview fragment";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recycler_view, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_in_fragment);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new MyAdapter(markerArrayList, this);
recyclerView.setAdapter(adapter);
return view;
Here is my xml for the recyclerview Fragment:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RecyclerView.RecyclerViewFragment"
android:background="#a6ffffff">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_in_fragment"
android:scrollbars="vertical"
android:layout_below="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Thanks very much if you can help.

You should use onViewCreated() to access the views
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_in_fragment);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new MyAdapter(markerArrayList, this);
recyclerView.setAdapter(adapter);
}

Related

Error on the second fragment with recycler view layout manager

I have a mainActivity with a fragment container which i set one of three fragments in it.
In each one i have a recycler view and I move to the next fragment on an item click.
The first fragment with the recyclerView is set as follows
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_courses, container, false);
mRootRef = FirebaseDatabase.getInstance().getReference();
mCoursesList = view.findViewById(R.id.courses_rv);
linearLayoutManager = new LinearLayoutManager(getContext());
mCoursesList.setLayoutManager(linearLayoutManager);
mCoursesList.setHasFixedSize(true);
updateView();
return view;
}
the error happens when entering the second fragment which is done as
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_subjects, container, false);
mSubjectsList = view.findViewById(R.id.subjects_rv);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
mSubjectsList.setLayoutManager(layoutManager);
mSubjectsList.setHasFixedSize(true);
Bundle bundle = this.getArguments();
if (bundle != null) {
courseName = bundle.getString( "CourseName");
subjectName = bundle.getString( "SubjectName");
}
// Inflate the layout for this fragment
return view;
}
Apparently they are the same but with the error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
The XML files
Main2Activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.crash.mathtest.Views.Main2Activity">
<LinearLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
></LinearLayout>
</LinearLayout>
CoureseFragment:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.crash.mathtest.Views.CoursesFragment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/courses_rv"
/>
</FrameLayout>
Subjects fragment is the same as courses fragment
Again, this only appears on the second fragment (onCreateView)
The error points to the setLayoutManager(linearLayout)
Can't I make new layouts in the same activity ?
doesn't the new one override the last ?
You don't need to declare twice setLayoutManager() method. You are doing:
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
mSubjectsList.setLayoutManager(layoutManager);
mSubjectsList.setLayoutManager(mSubjectsList.getLayoutManager());
Instead of this, just declare:
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
mSubjectsList.setLayoutManager(layoutManager);
Try to move your recyclerView data from onCreateView to onViewCreated.
Inside onCreateView() method:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.your_fragment, container, false);
}
Now add your recyclerView content to onViewCreated() method:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recyclerView = (RecyclerView) getActivity().findViewById(R.id.recyclerViewId);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
mSubjectsList.setLayoutManager(layoutManager);
}
UPDATE
do this stuff in
onActivityCreated from onCreateView
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
mSubjectsList.setLayoutManager(layoutManager);
mSubjectsList.setHasFixedSize(true);
Bundle bundle = this.getArguments();
if (bundle != null) {
courseName = bundle.getString( "CourseName");
subjectName = bundle.getString( "SubjectName");
}

Null pointer exception while setting up recycler view in fragment [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am getting this specific error during the runtime of my android app:
java.lang.NullPointerException: Attempt to invoke virtual method`'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at com.monkeyengineer.project.MyFragment.onCreateView(MyFragment.java:36)
I have checked the android recycler view and adapter documentation but it is not helping me with why this is crashing.
Here is my code in my Fragment where I am calling the findViewById method on the container view (import statements are omitted for brevity):
public class MyFragment extends Fragment {
private List<Project> data;
private RecyclerView recyclerView;
private TextView textView;
private boolean mIsRecyclerViewVisible = true;
public MyFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mView = inflater.inflate(R.layout.my_fragment, container, false);
textView = (TextView) container.findViewById(R.id.text_view);
recyclerView = (RecyclerView) container.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getContext());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLayoutManager);
Adapter adapter = new ProjectsAdapter(data);
recyclerView.setAdapter(adapter);
if (data != null) {
textView.setVisibility(View.INVISIBLE);
mIsRecyclerViewVisible = true;
} else {
recyclerView.setVisibility(View.INVISIBLE);
mIsRecyclerViewVisible = false;
}
return mView;
}
#Override
public void onStart() {
super.onStart();
if (mIsRecyclerViewVisible) {
recyclerView.setVisibility(View.VISIBLE);
textView.setVisibility(View.INVISIBLE);
} else {
recyclerView.setVisibility(View.INVISIBLE);
textView.setVisibility(View.VISIBLE);
}
}
#Override
public void onStop() {
super.onStop();
mIsRecyclerViewVisible = data != null;
}
}
Here is my fragment layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.monkeyengineer.project.MyFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
<TextView
android:id="#+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:height="45dp"
android:drawableLeft="#android:drawable/ic_input_add"
android:drawableStart="#android:drawable/ic_input_add"
android:drawablePadding="8dp"
android:gravity="start|center"
android:padding="8dp"
android:text="Add stuff."
android:textStyle="bold"
android:layout_gravity="center_horizontal"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
So why is it giving a null pointer exception, it must be because the recycler view object is being assigned to a null value but I can not think why.
Thanks.
You're inflating it wrong. Inflate the views from container to mView. Change like below:
textView = (TextView) mView.findViewById(R.id.text_view);
recyclerView = (RecyclerView) mView.findViewById(R.id.recycler_view);

My fragment keeps crashing when it is being refreshed

I want to refresh the fragment on a button click - i.e, destroy the fragment and force recall on onCreateView() method. However, it keeps crashing because of a GRRRR NullPointerException on the line fragment.getFragmentManager().findFragmentByTag("Frag1");
This is my code:
import android.app.ProgressDialog;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class UserListRecycler extends Fragment {
RecyclerView recyclerView;
static UserAdapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<UserInfo> list;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.userlistGUI, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.reUsers);
recyclerView.setHasFixedSize(true);
list = new ArrayList<UserInfo>();
// Instantiate new adapter here
adapter = new MusicRecyclerAdapter(list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
// Sets the adapter here
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return rootView;
}
#Override
public void onStart() {
super.onStart();
populateRecyclerList();
}
public void populateList(){
PopulateUsers userList = new PopulateUsers(list, adapter, recyclerView);
userList.execute();
}
public void recallFragment(){
Fragment fragment = null;
fragment.getFragmentManager().findFragmentByTag("TabOne");
getFragmentManager().beginTransaction()
.detach(fragment)
.attach(fragment)
.commit();
}
}
It is the recallFragment() method that is causing the issue. I want to recall on onCreateView() as that would physically refresh the fragment and redisplay the recyclerview. It is getting NullPointerException on fragment.getFragmentManager().findFragmentByTag("TabOne");. This is my stack trace:
java.lang.NullPointerException
at lukazs.usersapp.UserListRecycler.recallFragment()(TabOne.java:160)
at lukazs.usersapp.UserListRecycler$RecommendUser.onPostExecute(TabOne.java:300)
at lukazs.usersapp.UserListRecycler$RecommendUser.onPostExecute(TabOne.java:306)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
This is my onCreateView() method:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.userlistGUI, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.reUsers);
recyclerView.setHasFixedSize(true);
list = new ArrayList<UserInfo>();
// Instantiate new adapter here
adapter = new MusicRecyclerAdapter(list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
// Sets the adapter here
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return rootView;
}
UPDATED XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:id="#+id/rLayouts">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listFrag"
class="lukazs.usersapp.UserListRecycler"/>
<view
android:layout_width="wrap_content"
android:layout_height="wrap_content"
class="android.support.v4.view.ViewPager"
android:id="#+id/viewPager"
android:layout_alignParentStart="true" />
<android.support.v7.widget.RecyclerView
android:id="#+id/usersList"
android:layout_width="match_parent"
android:layout_height="420dp"
android:layout_gravity="center_horizontal|top"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
Fragment fragment = new WhatEverFragmentClassYouHave();
You set your fragment to null that is why you have a null exception.
If you're going to detach and then attach something. Just call replace() if you know how to use it.
<fragment
android:id="#+id/article_fragment"
android:layout_weight="2"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.example.android.fragments.ArticleFragment"
/>
For the Refresh
public void recallFragment(){
Fragment fragment = new WhatEverFragmentClass();
getFragmentManager().beginTransaction().replace(R.id.article_fragment,fragment,"MyFragmentTag").commit();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.userlistGUI, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = (RecyclerView) rootView.findViewById(R.id.reUsers);
recyclerView.setHasFixedSize(true);
list = new ArrayList<UserInfo>();
// Instantiate new adapter here
adapter = new MusicRecyclerAdapter(list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
// Sets the adapter here
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
Instead of detaching and attaching the fragment, you should either have an API in your fragment that tells it to refresh its content, or you should create a new instance of the fragment and replace the existing instance with the new one. Telling the fragment to refresh itself is obviously more efficient than destroying and creating a new fragment.

Vertical LinearLayoutManager Crashes App

So I am using two RecyclerViews in a fragment in my android app. One of them scrolls horizontally and the other scrolls vertically. Yet for some strange reason the vertical one always crashes with the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v7.widget.RecyclerView$LayoutManager.canScrollHorizontally()' on a null object reference
Here's how I set up the RecyclerViews:
#InjectView(R.id.nearby_recycler)
RecyclerView nearbyRecycler;
RecyclerView.LayoutManager nearbyLayoutManager;
#InjectView(R.id.buddies_recycler)
RecyclerView buddiesRecycler;
RecyclerView.LayoutManager buddiesLayoutManager;
public static HomeFragment newInstance(){
return new HomeFragment();
}
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View root = inflater.inflate(R.layout.fragment_home, container, false);
ButterKnife.inject(this, root);
nearbyLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
nearbyRecycler.setLayoutManager(nearbyLayoutManager);
nearbyRecycler.setAdapter(buddiesAdapter);
buddiesLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
buddiesRecycler.setLayoutManager(buddiesLayoutManager);
buddiesRecycler.setAdapter(buddiesAdapter);
return root;
}
The RecyclerViews in fragment_home.xml
<android.support.v7.widget.RecyclerView
android:id="#+id/nearby_recycler"
android:layout_width="match_parent"
android:layout_height="#dimen/icon_large"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/buddies_recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
As soon as I switch the orientation to Horizontal, the RecyclerView crashes as soon as I scroll it. Any suggestions?
I figured it out! So I'm completely unsure about why this was an issue, but the root of the problem was that my fragment was inside a view pager. I took it out of the view pager for now and added the fragment through fragment transaction.
My previous method of adding the fragment was this way.
MainActivity.java
HomeFragment homeFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
homeFragment = HomeFragment.newInstance();
mFragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(int position) {
return homeFragment;
}
#Override
public int getCount() {
return 1;
}
};
}
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
tools:context=".ui.MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_below="#id/toolbar1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
I changed it to this:
MainActivity.java
HomeFragment homeFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, homeFragment)
.commit();
}
}
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
tools:context=".ui.MainActivity">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>

RecyclerView + ViewPager NullPointerException on 'boolean android.support.v7.widget.RecyclerView$LayoutManager.canScrollHorizontally()'

I have an activity extending AppCompatActivity with a single fragment which contains RecyclerView. On any item click, it will replace this fragment with another fragment which contains ViewPager and fragments of ViewPager are again RecyclerView.
RecyclerViewFragment
ViewPagerFragment
I am getting following error(app crashes) on ViewPager fragment while scrolling the page.
E/InputEventReceiver: Exception dispatching input event.
E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v7.widget.RecyclerView$LayoutManager.canScrollHorizontally()' on a null object reference
E/MessageQueue-JNI: at android.support.v7.widget.RecyclerView.onInterceptTouchEvent(RecyclerView.java:2022)
E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2059)
E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent
.
.
.
E/AndroidRuntime: FATAL EXCEPTION: main
E/AndroidRuntime: Process: me.twig.twigme, PID: 23451
E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v7.widget.RecyclerView$LayoutManager.canScrollHorizontally()' on a null object reference
E/AndroidRuntime: at android.support.v7.widget.RecyclerView.onInterceptTouchEvent(RecyclerView.java:2022)
E/AndroidRuntime: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2059)
E/AndroidRuntime: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2432)
E/AndroidRuntime: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
Below is the code
RecyclerViewFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_cards, container, false);
}
#Override
public void onResume() {
super.onResume();
cardsRecyclerView = (RecyclerView) getActivity().findViewById(R.id.cards_recycler_view);
final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
cardsRecyclerView.setLayoutManager(layoutManager);
if(cardsRecyclerView.getAdapter() == null)
{
cardAdapter = new CardAdapter(getActivity().getApplicationContext(), getActivity(), new ArrayList<CardModel>());
cardsRecyclerView.setAdapter(cardAdapter);
}
// List initialization code
}
public static RecyclerViewFragment createInstance(String cardsJson) {
RecyclerViewFragment cardsListFragment = new RecyclerViewFragment();
Bundle args = new Bundle();
args.putString("cardsJson", cardsJson);
cardsListFragment.setArguments(args);
return cardsListFragment;
}
ViewPagerFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_cards_pager, container, false);
}
#Override
public void onStart() {
super.onStart();
tabLayout = (TabLayout) getActivity().findViewById(R.id.tabLayout);
tabLayout.removeAllTabs();
viewPager = (ViewPager) getActivity().findViewById(R.id.viewPager);
pagerAdapter = new PagerAdapter(getChildFragmentManager());
for( i=0; i<3; i++)
{
pagerAdapter.addFragment(RecyclerViewFragment.createInstance(cardsJson), "Tab title");
}
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
class PagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
fragmentList.clear();
fragmentTitleList.clear();
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
fragment_cards.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_frame_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/cards_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/ColorPrimaryLight"
android:clipToPadding="false"
xmlns:android="http://schemas.android.com/apk/res/android" />
</FrameLayout>
fragment_cards_pager.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/ColorPrimaryLight">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabTextColor="#android:color/white"
app:tabSelectedTextColor="#android:color/white"
app:tabIndicatorColor="#android:color/white"
app:tabIndicatorHeight="6dp"/>
</android.support.design.widget.AppBarLayout>
<ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
From aga's answer
This issue usually occurs when no LayoutManager was provided for the
RecyclerView. You can do it like so:
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
This solution is done programatically, but it means that you don't have any LayoutManager declared inside the RecyclerView.
Essentially, the given exception comes when the LayoutManager is not set on the RecyclerView.
I think your problem lies in following lines :
for( i=0; i<3; i++)
{
pagerAdapter.addFragment(RecyclerViewFragment.createInstance(cardsJson), "Tab title");
}
Using the same fragment in all three adjacent views is causing errors on swiping as ViewPager maintains the adjacent view states for swiping behavior. Use of same ids is also known to have cause similar problems. Try checking by rendering distinct fragments.
Also, displaying the same fragment in all the tabs doesn't look logical.

Categories

Resources