Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8659997
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T16:08:44+00:00 2026-06-12T16:08:44+00:00

first of all I readed some other threads talking about this, like this: Replace

  • 0

first of all I readed some other threads talking about this, like this:
Replace Fragment inside a ViewPager

I have a custom FragmentStackAdapter to manage all the Fragments of my application, the final request of the client is to show the tabs in all application so I decided to implement SherlockActionBar + tabs + viewpager (for slide).

I have the next implementation of FragmentStackAdapter:

public class FragmentStackAdapter extends FragmentPagerAdapter {

/**
 * Logging tag
 */
private final static String TAG = "FragmentStackAdapter";

/**
 * Fragment Manager
 */
private FragmentManager fm;

/**
 * Container of this adapter
 */
private ViewPager pager;

/**
 * Current tab position (SET THIS in the TAB LISTENER)
 */
private Integer currentTabPosition;

/**
 * Array of stacks to get fragment stack list.
 */
private SparseArray<LinkedList<Fragment>> stackFragments = new SparseArray<LinkedList<Fragment>>();

/**
 * Default constructor
 * @param fm FragmentManager
 */
public FragmentStackAdapter(FragmentManager fm, ViewPager pager) {

    super(fm);
    this.fm = fm;
    this.pager = pager;
}

public void addRootFragmentAtPosition(int tabPos, Fragment rootFragment) {

    if (tabPos > stackFragments.size() - 1) {
        stackFragments.put(tabPos, new LinkedList<Fragment>());
    }

    LinkedList<Fragment> stack = stackFragments.get(tabPos);
    stack.add(0, rootFragment);

}

public Fragment getRootFragment(int tabPos) {

    return stackFragments.get(tabPos).get(0);

}

public void addFragment(Fragment f) {

    startUpdate(pager);

    Tools.logLine(TAG, "addFragment(): Fragment:" + f + ", in position: " + currentTabPosition);
    LinkedList<Fragment> stack = stackFragments.get(currentTabPosition);
    Fragment last = stack.getLast();
    stack.addLast(f);

    fm.beginTransaction()
        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
        .remove(last)
        .add(pager.getId(), f)
        .commit();


    finishUpdate(pager);
    notifyDataSetChanged();

}

/**
 * Goes back in the current selected tab.
 * @return true if it goes back, false if cannot cause the stack is in the last element. Util for handle super.onPressback().
 */
public boolean back() {

    LinkedList<Fragment> stack = stackFragments.get(currentTabPosition);

    if (stack.size() > 1) {

        startUpdate(pager);

        Fragment currentFragment = stack.getLast();
        stack.removeLast();
        fm.beginTransaction()
            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
            .remove(currentFragment)
            .add(pager.getId(), stack.getLast())
        .commit();

        notifyDataSetChanged();
        finishUpdate(pager);

        return true;

    }

    return false;
}

@Override
public int getCount() {
    return stackFragments.size();
}

@Override
public Fragment getItem(int pos) {

    LinkedList<Fragment> stack = stackFragments.get(pos);

    Fragment last = stack.getLast();

    Tools.logLine(TAG, "getItem() pos: " + pos + ", fragment:" + last.toString() + ", isV:" + last.isVisible() + ", isD:" + last.isDetached());
    return last;

}

@Override
public int getItemPosition(Object object) {

    int size = stackFragments.size();
    for (int i = 0 ; i < size ; i++) {

        int key = stackFragments.keyAt(i);
        LinkedList<Fragment> stack = stackFragments.get(key);

        if (stack.contains(object)) {

            int indexOf = stack.indexOf(object);

            // is root activity and is the current selected tab
            if (key == currentTabPosition && indexOf == 0) {

                return POSITION_NONE; // force reload this fragment

            } else if (indexOf == 0) { // if root and other, no changes

                return POSITION_UNCHANGED;

            }

            Tools.logLine(TAG, "getItemPos:, indexOf: " + indexOf + ", Object:" + object.toString());
            return indexOf; // return the pos of the activity

        }

    }

    Tools.logLine(TAG, "getItemPos: RETURN DEFAULTTTTT POSITION_NONE, " + object.toString()); 

    return POSITION_NONE; // the current item is not in the stack, so probabilly we removed it pressing back. Reload this tab will get another getItem and return the new corresponding item

}

@Override
public CharSequence getPageTitle(int position) {

    return "Near";

}

@Override
public long getItemId(int position) {

    LinkedList<Fragment> stack = stackFragments.get(position);
    Fragment f = stack.getLast();

    int rtnid = f.hashCode();

    Tools.logLine(TAG, "getItemId() for pos: " + position + ", Fragment: "+ f  +", rtnId: " + rtnid + ", hex: " + Integer.toString(rtnid, 16));

    return rtnid;

}

public void setCurrentTabPostion(int currentTabPosition) {
    this.currentTabPosition = currentTabPosition;
}
    }

And this is how I initialize from my MainActivity:

// Assign ui fieds
viewPager = (ViewPager)findViewById(R.id.pager);

    // Configure the StackAdapter
    fragmentAdapter = new FragmentStackAdapter(getSupportFragmentManager(), viewPager);
    fragmentAdapter.addRootFragmentAtPosition(TIMELINE_TAG, new TimelineActivity());
    fragmentAdapter.addRootFragmentAtPosition(NEAR_TAG, new NearFragment());

I think it works OK when i Call fragmentAdapter.addFragment() It shows the new fragment in the previously loaded fragment but it fails when I handle the “back()” method showing this stacktrace:

        did=1: thread exiting with uncaught exception (group=0x400205a0)
         FATAL EXCEPTION: main
         java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
            at android.view.ViewGroup.addViewInner(ViewGroup.java:2062)
            at android.view.ViewGroup.addView(ViewGroup.java:1957)
            at android.view.ViewGroup.addView(ViewGroup.java:1914)
            at android.view.ViewGroup.addView(ViewGroup.java:1894)
            at android.support.v4.app.NoSaveStateFrameLayout.wrap(NoSaveStateFrameLayout.java:40)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:875)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1083)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:635)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1431)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:431)
            at com.bbva.tweetmeter.ui.FragmentStackAdapter.getItemPosition(FragmentStackAdapter.java:311)
            at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:712)
            at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:2519)
            at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:31)
            at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:276)
            at com.bbva.tweetmeter.ui.FragmentStackAdapter.back(FragmentStackAdapter.java:154)
            at com.bbva.tweetmeter.ui.MainActivity.onBackPressed(MainActivity.java:210)
            at android.app.Activity.onKeyUp(Activity.java:1985)
            at android.view.KeyEvent.dispatch(KeyEvent.java:1513)
            at android.app.Activity.dispatchKeyEvent(Activity.java:2210)
            at com.actionbarsherlock.app.SherlockFragmentActivity.dispatchKeyEvent(SherlockFragmentActivity.java:122)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1769)
            at android.view.ViewRoot.deliverKeyEventToViewHierarchy(ViewRoot.java:2716)
            at android.view.ViewRoot.handleFinishedEvent(ViewRoot.java:2688)
            at android.view.ViewRoot.handleMessage(ViewRoot.java:1969)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:143)
            at android.app.ActivityThread.main(ActivityThread.java:4293)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:507)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
            at dalvik.system.NativeStart.main(Native Method)

Why shows this trace if I replace the previous fragment why have parent attached? Any way to handle this ?

Feel free to ask if I dont explained correctly

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T16:08:46+00:00Added an answer on June 12, 2026 at 4:08 pm

    It was a problem of the onCreateView implementation of fragments. I was returning same View saved in a instance variable allways, then when the fragment is re-attaching it calls to onCreateView another time but returning the same View so this view already has a parent. The correct implementation is recreate other view instead of save in a instance variable the previous view.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

First of all, apologize because I have seen some posts about this, but I
First of all there is probably a question like this already but i couldn't
I have some large csv file, with about 200 header names (the first one
First of all, this isn't for a keylogger, it's for an input in a
first of all some details: I configured security as below in web.xml view plaincopy
first of all i would like to say i know its probably an easy
I readed some tutorials about making droplets with apple script or with automator's help.
this is some kind of long post, so I have to say thanks for
I'll start off by saying I'm a noob with all of this, I have
First let me start by thanking you all for being part of this site,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.