FragmentManager is already executing transactions. While using fragment in android - android

Iam using a Viewpager inside a fragment. And the viewpager is initialized after the fragment is created. The viewpager has two tabs.
But while i am setting the adapter for the viewpager "FragmentManager is already executing transactions." this error comes up.
Error is as follows.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.lalrentals.app.lalrentals, PID: 26248
java.lang.IllegalStateException: FragmentManager is already executing transactions
Java class :
public class HomeFr extends Fragment
{
public HomeFr(){
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//ADDING VIEWPAGER
ViewPager viewPager = getActivity().findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new HomeFr(), "Home");
adapter.addFragment(new PostAddFr(), "Post");
viewPager.setAdapter(adapter);
//SETTING TAB FOR THE VIEWPAGER
TabLayout tabLayout = getActivity().findViewById(R.id.tab);
tabLayout.setupWithViewPager(viewPager);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = LayoutInflater.from(getActivity()).inflate(R.layout.frag_home,null);
return v;
}
//ADAPTER FOR THE VIEWPAGER
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}

I'm not totally sure if this is the root cause but I think following point is wrong:
adapter.addFragment(new HomeFr(), "Home");
adapter.addFragment(new PostAddFr(), "Post");
Inside HomeFr fragment you are adding HomeFr again. Instead, you should have a "generic" Fragment which will host HomeFr and PostAddFr.
So, in the end, you should have 3 fragments:
Host which will be the parent Fragment and this fragment is responsible to instantiate the view pager
HomeFr one of the Fragments displayed by the view pager
PostAddFr one of the Fragments displayed by the view pager
Something like:
HostFr
public class HostFr extends Fragment {
public HostFr(){
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
....
adapter.addFragment(new HomeFr(), "Home");
adapter.addFragment(new PostAddFr(), "Post");
....
}
.....
class ViewPagerAdapter extends FragmentPagerAdapter {
....
}
}
HomeFr
public class HomeFr extends Fragment {
...
// HomeFr Views
...
}
PostAddFr
public class PostAddFr extends Fragment {
...
// PostAddFr Views
...
}

Related

cannot find fragment from viewpager

there is a fragment in my activity in which there is a viewpager which has 5 fragments in it and inside the main activity i need to get one of the fragment from viewpager
Activity
public class MainActivity extends AppCompatActivity {
public void setFragment(){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mainFragment= new MainFragment();
FragmentTransaction fragmentTransaction =getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, mainFragment,"mainFragment");
fragmentTransaction.commitAllowingStateLoss();
}
}, 250);
}
public void findFragment() {
mainFragment= (MainFragment) getSupportFragmentManager().findFragmentByTag("mainFragment");
viewPager = mainFragment.viewPager;
FragmentOne fragment = (FragmentOne) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + viewPager.getCurrentItem());
}
}
MainFragment
public class MainFragment extends Fragment{
private void initViewPagerAndTabs() {
viewPager = view.findViewById(R.id.viewPager);
pagerAdapter = new PagerAdapter(getChildFragmentManager());
pagerAdapter.addFragment(FragmentOne.newInstance(), "one");
pagerAdapter.addFragment(FragmentTwo.newInstance(), "two");
pagerAdapter.addFragment(FragmentThree.newInstance(), "three");
pagerAdapter.addFragment(FragmentFour.newInstance(), "four");
pagerAdapter.addFragment(FragmentFive.newInstance(), "five");
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = view.findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(1);
viewPager.setOffscreenPageLimit(3);
}
private static class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
private PagerAdapter(FragmentManager fm) {
super(fm);
}
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);
}
}
}
if i use "getFragmentManager()" instead of "getChildFragmentManager()" then it returns the fragment but when i use "getChildFragmentManager()" in viewPager it returns null in activity
Try this Running Code for 1 fragment, may it helps you in your code :
Main Activity
public class OpenQuran extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
TabLayout tabLayoutqaue;
Pager mAdapter;
MediaPlayer mp;
//This is our viewPagerss
ViewPager viewPager;
View mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_quran);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Read Quran");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Initializing the tablayout
tabLayoutqaue = (TabLayout) findViewById(R.id.tabLayoutqaue);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
mAdapter = new Pager(getSupportFragmentManager());
// 1 Fragment
mAdapter .addFrag(new Quran(), "Quran");
viewPager.setAdapter(mAdapter);
tabLayoutqaue.setupWithViewPager(viewPager);
tabLayoutqaue.setOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
Fargment Class :
public class parahlist extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
return inflater.inflate(R.layout.activity_parahlist, container, false);}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
View Pager Class:
public class Pager extends FragmentPagerAdapter {
//integer to count number of tabs
int tabCount;
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
//Constructor to the class
public Pager(FragmentManager fm) {
super(fm);
//Initializing tab count
this.tabCount= tabCount;
}
//Overriding method getItem
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment Fragment, String title) {
mFragmentList.add(Fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Now This the code Of MainActivity, 2nd Fragment and 3rd one is View Pager class. You dont need to change or edit your View Pager Class. Just Create Java Class and Paste that code as it is.
In Main Activity the Line : mAdapter .addFrag(new Quran(), "Quran"); adding description and Fragment. You can add your own fragment after "new".
After that you have to put Tablayout widget in you Xml as Follows:
<android.support.design.widget.TabLayout
android:id="#+id/tabLayoutqaue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorgreen"
android:minHeight="?attr/actionBarSize"
app:tabIndicatorColor="#color/colorback"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
And View Pager like:
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
/>
You may face some issue regarding tablayout :
Just put this line in your gradle build under dependecies:
compile 'com.android.support:design:25.3.1'
According to your version. for example you have 25.0.1
then line will be :
compile 'com.android.support:design:25.0.1
Still i m here to tell you more. if you got problem!

How to refresh the Pager tab fragment in android?

I have to refresh the fragment when I swipe to another fragment from the Tab.
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
mBinding = DataBindingUtil.inflate(inflater, R.layout.manage_work_shop_act, container, false);
mBinding.layout.title.setText(getString(R.string.d_manage_my_staff));
mBinding.tabs.setupWithViewPager(mBinding.viewpager);
setupViewPager(mBinding.viewpager);
mBinding.layout.nav.setVisibility(View.GONE);
mBinding.layout.navMenu.setVisibility(View.VISIBLE);
mBinding.layout.navMenu.setOnClickListener(view -> openDrawer());
return mBinding.getRoot();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
int limit = (adapter.getCount() > 1 ? adapter.getCount() - 1 : 1);
adapter.addFragment(new MechanicListFragment(), getString(R.string.d_manage_my_staff));
adapter.addFragment(new MechanicNewFragment(), getString(R.string.new_frag));
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(limit);
adapter.notifyDataSetChanged();
}
My Adapter is like this
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
I tried all the ways to refresh my fragment.
If I swipe the tab or click the another tab then I need to refresh the visible tab again.
In my current fragment did not refresh.
please help me to override from this issue.
Try using Fragment state pager adapter than fragment adapter when you have to refresh tabs in your adapdter.
FragmentPagerAdapter stores the previous data which is fetched from the adapter while FragmentStatePagerAdapter takes the new value from the adapter everytime it is executed.
There's onHiddenChanged method in the fragment.
Called when the hidden state (as returned by isHidden() of the
fragment has changed. Fragments start out not hidden; this will be
called whenever the fragment changes state from that.
override the onHiddenChanged method in each of your tab fragment and if is not hidden do the refreshing. For example:
class YourFragment extends Fragment {
#Override public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (!hidden) {
//you can refresh here now
}
}
}

handling fragment after manually phone lock in View pager

Actually, i am implementing a TabLayout, so in main MainActivity, I load the TabFragment and in the tabFragment(contain two fragments) I used the ViewPager.
So the problem is when I am on fragment two in TabLayout and the after the screen goes off it will move to the Fragment one(Default one). So how can I tackle this one
Here is TabFragment Code:
public class TabFragment extends Fragment {
public TabFragment() {
// Required empty public constructor
}
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View x=inflater.inflate(R.layout.content_main_menu,null);
tabLayout=(TabLayout) x.findViewById(R.id.tabs);
viewPager =(ViewPager) x.findViewById(R.id.viewpager);
setupViewPager(viewPager);
//viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
viewPager.setOffscreenPageLimit(1);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
private void setupViewPager(ViewPager viewPager) {
MyAdapter adapter = new MyAdapter(getChildFragmentManager());
adapter.addFragment(new HomeFragment(), "Fragment One");
adapter.addFragment(new Offers(), "fragment Two");
viewPager.setAdapter(adapter);
}
class MyAdapter extends FragmentPagerAdapter{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Use FragmentStatePagerAdapter instead of FragmentPagerAdapter. read documentation here. FragmentStatePagerAdapter only stores the savedInstanceState of fragments, and destroys all the fragments when they lose focus.

How can i add different data to 3 fragment in 3 tabs?

i want to know that how can i add some different data like an array to each fragments that are in TabLayout?
i mean that fragment1 show array1, fragment2 show array2 and fragment3 show array3
the below is my code for Tablayout:
public class PoshtibaniActivity extends AppCompatActivity {
private Toolbar toolbar;
private ViewPager mPager;
private SlidingTabLayout mTabs;
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poshtibani);
toolbar = (Toolbar) findViewById(R.id.app_bar_empty);
//setSupportActionBar(toolbar);
toolbar.setTitle("پشتیبانی");
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mPager = (ViewPager) findViewById(R.id.pager);
setupViewPager(mPager);
mPager.setCurrentItem(2);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentOne(), "پیامهای دریافتی");
adapter.addFragment(new FragmentTwo(), "پیامهای ارسالی");
adapter.addFragment(new FragmentThree(), "ارسال پیام");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
you should use SetArguement for each of your fragments.
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentOne(), "پیامهای دریافتی",MY_ARRAY_1,MY_SEC_ARRAY_1);
adapter.addFragment(new FragmentTwo(), "پیامهای ارسالی",MY_ARRAY_2,MY_SEC_ARRAY_2);
adapter.addFragment(new FragmentThree(), "ارسال پیام",MY_ARRAY_3,MY_SEC_ARRAY_3);
viewPager.setAdapter(adapter);
}
then in your adapter :
public void addFragment(Fragment fragment, String title,Object data,ArrayList<MY_DATA_MODEL> array2) {
Bundle mBundle=new Bundle();
mBundle.put("dataArray",data);
mBundle.put("dataArray2",array2);
fragment.setArgument(mBundle);
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
Now in each of your fragments, you should override setArguments and get your data from bundle there.
Don't forget to make your data model parcelable if you want to pass them in bundle and intents.
view pager file
public class SamplePagerAdapter extends FragmentPagerAdapter {
String[] title = {
"stringA",
"stringB",
"stringC",
}
public SamplePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
/** Show a Fragment based on the position of the current screen */
if (position == 0) {
return FragmentA.newInstance(title);
}
else if(position==1)
{
return new FragmentB.newInstance(title);
}
else { return FragmentC.newInstance(title);}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
Fragment file
public class FragmentA extends Fragment {
public static FragmentA newInstance(String [] s) {
FragmentA A = new FragmentA();
Bundle args = new Bundle();
args.putStringArrayList("elist",s);
A.setArgumentas(args);
return A;
}
}
public View onCreateView(LayoutInflater inflater,
ViewGroup containerObject,
Bundle savedInstanceState){
//here is your arguments
Bundle bundle=getArguments();
//here is your list array
String[] myStrings=bundle.getStringArray("elist");
}
public class FragmentB extends Fragment {
public static FragmentB newInstance(String [] s) {
FragmentB B = new FragmentB();
Bundle args = new Bundle();
args.putStringArrayList("elist",s);
B.setArgumentas(args);
return B;
}
}
public View onCreateView(LayoutInflater inflater,
ViewGroup containerObject,
Bundle savedInstanceState){
//here is your arguments
Bundle bundle=getArguments();
//here is your list array
String[] myStrings=bundle.getStringArray("elist");
}
public class FragmentC extends Fragment {
public static FragmentC newInstance(String [] s) {
FragmentC C = new FragmentC();
Bundle args = new Bundle();
args.putStringArrayList("elist",s);
C.setArgumentas(args);
return C;
}
}
public View onCreateView(LayoutInflater inflater,
ViewGroup containerObject,
Bundle savedInstanceState){
//here is your arguments
Bundle bundle=getArguments();
//here is your list array
String[] myStrings=bundle.getStringArray("elist");
}

View is not inflated on returning to the tab fragment

I have one activity named rootActivity , in which i have a rootContainer in which i replace the fragments.
Now, the first fragment that i replace is DashboardFragment.
I now click on the cross to open a new fragment like this...
Now when i press the back button the content of dashboard fragment is lost.
Can someone help me
Here's a video to show what's really happening.
https://youtu.be/NobqYUCEZKY
Code for the DashboardFragment(contains the fragments inside tabs)
public class DashboardFragment extends Fragment {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private View rootView;
/**
*
* #param config : For setting up stuff by the given config
* #return
*/
public static DashboardFragment newInstance(Bundle config) {
DashboardFragment fragment = new DashboardFragment();
fragment.setArguments(config);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_dashboard, container, false);
toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((RootActivity)getActivity()).setSupportActionBar(toolbar);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
return rootView;
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(android.R.drawable.btn_star_big_off);
tabLayout.getTabAt(1).setIcon(android.R.drawable.btn_star_big_on);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
adapter.addFragment(new TrackeesFragment(), "Trackee");
adapter.addFragment(new TrackersFragment(), "Trackers");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
#Override
public CharSequence getPageTitle(int position) {
return null;
}
}
}
try by changing the following line in
setupViewPager(ViewPager viewPager) {}
Change
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
To
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());

Categories

Resources