Example usage for android.app FragmentManager getBackStackEntryAt

List of usage examples for android.app FragmentManager getBackStackEntryAt

Introduction

In this page you can find the example usage for android.app FragmentManager getBackStackEntryAt.

Prototype

public abstract BackStackEntry getBackStackEntryAt(int index);

Source Link

Document

Return the BackStackEntry at index index in the back stack; where the item on the bottom of the stack has index 0.

Usage

From source file:org.opendatakit.survey.activities.MainMenuActivity.java

private void popBackStack() {
    FragmentManager mgr = getFragmentManager();
    int idxLast = mgr.getBackStackEntryCount() - 2;
    if (idxLast < 0) {
        Intent result = new Intent();
        // If we are in a WEBKIT, return the instanceId and the savepoint_type...
        if (this.getInstanceId() != null && currentFragment == ScreenList.WEBKIT) {
            result.putExtra("instanceId", getInstanceId());
            // in this case, the savepoint_type is null (a checkpoint).
        }/*  w  ww.  j  a v  a2s .  c  om*/
        this.setResult(RESULT_OK, result);
        finish();
    } else {
        BackStackEntry entry = mgr.getBackStackEntryAt(idxLast);
        swapToFragmentView(ScreenList.valueOf(entry.getName()));
    }
}

From source file:de.sourcestream.movieDB.MainActivity.java

/**
 * Pops the last item from the back stack.
 * If searchView is opened it hides it.//  ww  w  .  j a v  a  2 s  .c om
 * reAttachMovieFragments re-creates our fragments this is due to a bug in the viewPager
 * restoreMovieDetailsState -> when we press back button we would like to restore our previous (if any)
 * saved state for the current fragment. We use custom backStack since the original doesn't save fragment's state.
 */
@Override
public void onBackPressed() {
    FragmentManager fm = getFragmentManager();

    if (mDrawerLayout.isDrawerOpen(mDrawerList))
        mDrawerLayout.closeDrawer(mDrawerList);
    else {
        if (searchViewItem.isActionViewExpanded())
            searchViewItem.collapseActionView();

        else if (fm.getBackStackEntryCount() > 0) {
            String backStackEntry = fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName();
            if (backStackEntry.equals("movieList"))
                reAttachMovieFragments = true;

            if (backStackEntry.equals("TVList"))
                reAttachTVFragments = true;

            if (backStackEntry.equals("searchList:1"))
                reAttachMovieFragments = true;

            if (backStackEntry.equals("searchList:2"))
                reAttachTVFragments = true;

            restoreMovieDetailsState = true;
            restoreMovieDetailsAdapterState = false;
            if (orientationChanged)
                restoreMovieDetailsAdapterState = true;

            fm.popBackStack();
        } else {
            super.onBackPressed();
        }
    }

}

From source file:org.opendatakit.survey.android.activities.MainMenuActivity.java

@Override
public void onBackPressed() {
    FragmentManager mgr = getFragmentManager();
    int idxLast = mgr.getBackStackEntryCount() - 2;
    if (idxLast < 0) {
        Intent result = new Intent();
        // If we are in a WEBKIT, return the instanceId and the savepoint_type...
        if (this.getInstanceId() != null && currentFragment == ScreenList.WEBKIT) {
            result.putExtra("instanceId", getInstanceId());
            // in this case, the savepoint_type is null (a checkpoint).
        }//from ww  w.  ja v  a 2  s . c om
        this.setResult(RESULT_OK, result);
        finish();
    } else {
        BackStackEntry entry = mgr.getBackStackEntryAt(idxLast);
        swapToFragmentView(ScreenList.valueOf(entry.getName()));
    }
}

From source file:de.sourcestream.movieDB.MainActivity.java

/**
 * First configure the Universal Image Downloader,
 * then we set the main layout to be activity_main.xml
 * and we add the slide menu items.//from www  .ja v  a  2  s.  co  m
 *
 * @param savedInstanceState If non-null, this activity is being re-constructed from a previous saved state as given here.
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    mTitle = mDrawerTitle = getTitle();

    // load slide menu items
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
    ViewGroup header = (ViewGroup) getLayoutInflater().inflate(R.layout.drawer_header, null, false);
    ImageView drawerBackButton = (ImageView) header.findViewById(R.id.drawerBackButton);
    drawerBackButton.setOnClickListener(onDrawerBackButton);
    mDrawerList.addHeaderView(header);
    mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
    // setting the nav drawer list adapter
    mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, R.id.title, navMenuTitles));

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
        toolbar.bringToFront();
    }

    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            toolbar, R.string.app_name, // nav drawer open - description for accessibility
            R.string.app_name // nav drawer close - description for accessibility
    ) {
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            // calling onPrepareOptionsMenu() to show search view
            invalidateOptionsMenu();
            syncState();
        }

        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            // calling onPrepareOptionsMenu() to hide search view
            invalidateOptionsMenu();
            syncState();
        }

        // updates the title, toolbar transparency and search view
        public void onDrawerSlide(View drawerView, float slideOffset) {
            super.onDrawerSlide(drawerView, slideOffset);
            if (slideOffset > .55 && !isDrawerOpen) {
                // opening drawer
                // mDrawerTitle is app title
                getSupportActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu();
                isDrawerOpen = true;
            } else if (slideOffset < .45 && isDrawerOpen) {
                // closing drawer
                // mTitle is title of the current view, can be movies, tv shows or movie title
                getSupportActionBar().setTitle(mTitle);
                invalidateOptionsMenu();
                isDrawerOpen = false;
            }
        }

    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    // Get the action bar title to set padding
    TextView titleTextView = null;

    try {
        Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
        f.setAccessible(true);
        titleTextView = (TextView) f.get(toolbar);
    } catch (NoSuchFieldException e) {

    } catch (IllegalAccessException e) {

    }
    if (titleTextView != null) {
        float scale = getResources().getDisplayMetrics().density;
        titleTextView.setPadding((int) scale * 15, 0, 0, 0);
    }

    phone = getResources().getBoolean(R.bool.portrait_only);

    searchDB = new SearchDB(getApplicationContext());

    if (savedInstanceState == null) {
        // Check orientation and lock to portrait if we are on phone
        if (phone) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        // on first time display view for first nav item
        displayView(1);

        // Use hockey module to check for updates
        checkForUpdates();

        // Universal Loader options and configuration.
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
                .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
                .showImageOnLoading(R.drawable.placeholder_default)
                .showImageForEmptyUri(R.drawable.placeholder_default)
                .showImageOnFail(R.drawable.placeholder_default).cacheOnDisk(true).build();
        Context context = this;
        File cacheDir = StorageUtils.getCacheDirectory(context);
        // Create global configuration and initialize ImageLoader with this config
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .diskCache(new UnlimitedDiscCache(cacheDir)) // default
                .defaultDisplayImageOptions(options).build();
        ImageLoader.getInstance().init(config);

        // Check cache size
        long size = 0;
        File[] filesCache = cacheDir.listFiles();
        for (File file : filesCache) {
            size += file.length();
        }
        if (cacheDir.getUsableSpace() < MinFreeSpace || size > CacheSize) {
            ImageLoader.getInstance().getDiskCache().clear();
            searchDB.cleanSuggestionRecords();
        }

    } else {
        oldPos = savedInstanceState.getInt("oldPos");
        currentMovViewPagerPos = savedInstanceState.getInt("currentMovViewPagerPos");
        currentTVViewPagerPos = savedInstanceState.getInt("currentTVViewPagerPos");
        restoreMovieDetailsState = savedInstanceState.getBoolean("restoreMovieDetailsState");
        restoreMovieDetailsAdapterState = savedInstanceState.getBoolean("restoreMovieDetailsAdapterState");
        movieDetailsBundle = savedInstanceState.getParcelableArrayList("movieDetailsBundle");
        castDetailsBundle = savedInstanceState.getParcelableArrayList("castDetailsBundle");
        tvDetailsBundle = savedInstanceState.getParcelableArrayList("tvDetailsBundle");
        currOrientation = savedInstanceState.getInt("currOrientation");
        lastVisitedSimMovie = savedInstanceState.getInt("lastVisitedSimMovie");
        lastVisitedSimTV = savedInstanceState.getInt("lastVisitedSimTV");
        lastVisitedMovieInCredits = savedInstanceState.getInt("lastVisitedMovieInCredits");
        saveInMovieDetailsSimFragment = savedInstanceState.getBoolean("saveInMovieDetailsSimFragment");

        FragmentManager fm = getFragmentManager();
        // prevent the following bug: go to gallery preview -> swap orientation ->
        // go to movies list -> swap orientation -> action bar bugged
        // so if we are not on gallery preview we show toolbar
        if (fm.getBackStackEntryCount() == 0
                || !fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName().equals("galleryList")) {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    if (getSupportActionBar() != null && !getSupportActionBar().isShowing())
                        getSupportActionBar().show();
                }
            });
        }
    }

    // Get reference for the imageLoader
    imageLoader = ImageLoader.getInstance();

    // Options used for the backdrop image in movie and tv details and gallery
    optionsWithFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(500))
            .imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false).showImageOnLoading(R.color.black)
            .showImageForEmptyUri(R.color.black).showImageOnFail(R.color.black).cacheOnDisk(true).build();
    optionsWithoutFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.color.black).showImageForEmptyUri(R.color.black)
            .showImageOnFail(R.color.black).cacheOnDisk(true).build();

    // Options used for the backdrop image in movie and tv details and gallery
    backdropOptionsWithFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(500))
            .imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.drawable.placeholder_backdrop)
            .showImageForEmptyUri(R.drawable.placeholder_backdrop)
            .showImageOnFail(R.drawable.placeholder_backdrop).cacheOnDisk(true).build();
    backdropOptionsWithoutFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.drawable.placeholder_backdrop)
            .showImageForEmptyUri(R.drawable.placeholder_backdrop)
            .showImageOnFail(R.drawable.placeholder_backdrop).cacheOnDisk(true).build();

    trailerListView = new TrailerList();
    galleryListView = new GalleryList();

    if (currOrientation != getResources().getConfiguration().orientation)
        orientationChanged = true;

    currOrientation = getResources().getConfiguration().orientation;

    iconConstantSpecialCase = 0;
    if (phone) {
        iconMarginConstant = 0;
        iconMarginLandscape = 0;
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;
        if (width <= 480 && height <= 800)
            iconConstantSpecialCase = -70;

        // used in MovieDetails, CastDetails, TVDetails onMoreIconClick
        // to check whether the animation should be in up or down direction
        threeIcons = 128;
        threeIconsToolbar = 72;
        twoIcons = 183;
        twoIconsToolbar = 127;
        oneIcon = 238;
        oneIconToolbar = 182;
    } else {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            iconMarginConstant = 232;
            iconMarginLandscape = 300;

            threeIcons = 361;
            threeIconsToolbar = 295;
            twoIcons = 416;
            twoIconsToolbar = 351;
            oneIcon = 469;
            oneIconToolbar = 407;
        } else {
            iconMarginConstant = 82;
            iconMarginLandscape = 0;

            threeIcons = 209;
            threeIconsToolbar = 146;
            twoIcons = 264;
            twoIconsToolbar = 200;
            oneIcon = 319;
            oneIconToolbar = 256;
        }

    }

    dateFormat = android.text.format.DateFormat.getDateFormat(this);
}

From source file:org.opendatakit.survey.activities.MainMenuActivity.java

public void swapToFragmentView(ScreenList newScreenType) {
    WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView: " + newScreenType.name());
    FragmentManager mgr = getFragmentManager();
    FragmentTransaction trans = null;/*from   w  ww  .  j  ava 2s  .  c o  m*/
    Fragment newFragment = null;
    if (newScreenType == ScreenList.MAIN_SCREEN) {
        throw new IllegalStateException("unexpected reference to generic main screen");
    } else if (newScreenType == ScreenList.FORM_CHOOSER) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            newFragment = new FormChooserListFragment();
        }
    } else if (newScreenType == ScreenList.FRONT_PAGE) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            newFragment = new FrontPageFragment();
        }
    } else if (newScreenType == ScreenList.INITIALIZATION_DIALOG) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            newFragment = new InitializationFragment();
        }
    } else if (newScreenType == ScreenList.WEBKIT) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            WebLogger.getLogger(getAppName()).i(t,
                    "[" + this.hashCode() + "] creating new webkit fragment " + newScreenType.name());
            newFragment = new WebViewFragment();
        }
    } else if (newScreenType == ScreenList.ABOUT_MENU) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            newFragment = new AboutMenuFragment();
        }

    } else {
        throw new IllegalStateException("Unrecognized ScreenList type");
    }

    boolean matchingBackStackEntry = false;
    for (int i = 0; i < mgr.getBackStackEntryCount(); ++i) {
        BackStackEntry e = mgr.getBackStackEntryAt(i);
        WebLogger.getLogger(getAppName()).i(t, "BackStackEntry[" + i + "] " + e.getName());
        if (e.getName().equals(newScreenType.name())) {
            matchingBackStackEntry = true;
        }
    }

    if (matchingBackStackEntry) {
        if (trans != null) {
            WebLogger.getLogger(getAppName()).e(t, "Unexpected active transaction when popping state!");
            trans = null;
        }
        // flush backward, to the screen we want to go back to
        currentFragment = newScreenType;
        WebLogger.getLogger(getAppName()).e(t,
                "[" + this.hashCode() + "] popping back stack " + currentFragment.name());
        mgr.popBackStackImmediate(currentFragment.name(), 0);
    } else {
        // add transaction to show the screen we want
        if (trans == null) {
            trans = mgr.beginTransaction();
        }
        currentFragment = newScreenType;
        trans.replace(R.id.main_content, newFragment, currentFragment.name());
        WebLogger.getLogger(getAppName()).i(t,
                "[" + this.hashCode() + "] adding to back stack " + currentFragment.name());
        trans.addToBackStack(currentFragment.name());
    }

    // and see if we should re-initialize...
    if ((currentFragment != ScreenList.INITIALIZATION_DIALOG)
            && ((Survey) getApplication()).shouldRunInitializationTask(getAppName())) {
        WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView -- calling clearRunInitializationTask");
        // and immediately clear the should-run flag...
        ((Survey) getApplication()).clearRunInitializationTask(getAppName());
        // OK we should swap to the InitializationFragment view
        // this will skip the transition to whatever screen we were trying to 
        // go to and will instead show the InitializationFragment view. We
        // restore to the desired screen via the setFragmentToShowNext()
        //
        // NOTE: this discards the uncommitted transaction.
        // Robolectric complains about a recursive state transition.
        if (trans != null) {
            trans.commit();
        }
        swapToFragmentView(ScreenList.INITIALIZATION_DIALOG);
    } else {
        // before we actually switch to a WebKit, be sure
        // we have the form definition for it...
        if (currentFragment == ScreenList.WEBKIT && getCurrentForm() == null) {
            // we were sent off to the initialization dialog to try to
            // discover the form. We need to inquire about the form again
            // and, if we cannot find it, report an error to the user.
            final Uri uriFormsProvider = FormsProviderAPI.CONTENT_URI;
            Uri uri = getIntent().getData();
            Uri formUri = null;

            if (uri.getScheme().equalsIgnoreCase(uriFormsProvider.getScheme())
                    && uri.getAuthority().equalsIgnoreCase(uriFormsProvider.getAuthority())) {
                List<String> segments = uri.getPathSegments();
                if (segments != null && segments.size() >= 2) {
                    String appName = segments.get(0);
                    setAppName(appName);
                    String tableId = segments.get(1);
                    String formId = (segments.size() > 2) ? segments.get(2) : null;
                    formUri = Uri.withAppendedPath(Uri.withAppendedPath(
                            Uri.withAppendedPath(FormsProviderAPI.CONTENT_URI, appName), tableId), formId);
                } else {
                    swapToFragmentView(ScreenList.FRONT_PAGE);
                    createErrorDialog(getString(R.string.invalid_uri_expecting_n_segments, uri.toString(), 2),
                            EXIT);
                    return;
                }
                // request specifies a specific formUri -- try to open that
                FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), formUri);
                if (newForm == null) {
                    // error
                    swapToFragmentView(ScreenList.FRONT_PAGE);
                    createErrorDialog(getString(R.string.form_not_found, segments.get(1)), EXIT);
                    return;
                } else {
                    transitionToFormHelper(uri, newForm);
                }
            }
        }

        if (trans != null) {
            trans.commit();
        }
        invalidateOptionsMenu();
    }
}

From source file:org.opendatakit.survey.android.activities.MainMenuActivity.java

public void swapToFragmentView(ScreenList newFragment) {
    WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView: " + newFragment.toString());
    FragmentManager mgr = getFragmentManager();
    Fragment f;/*from   www . j  a  v  a2  s. c o m*/
    if (newFragment == ScreenList.MAIN_SCREEN) {
        throw new IllegalStateException("unexpected reference to generic main screen");
    } else if (newFragment == ScreenList.CUSTOM_VIEW) {
        WebLogger.getLogger(getAppName()).w(t,
                "swapToFragmentView: changing navigation to move to WebKit (was custom view)");
        f = mgr.findFragmentById(WebViewFragment.ID);
        if (f == null) {
            f = new WebViewFragment();
        }
        newFragment = ScreenList.WEBKIT;
    } else if (newFragment == ScreenList.FORM_CHOOSER) {
        f = mgr.findFragmentById(FormChooserListFragment.ID);
        if (f == null) {
            f = new FormChooserListFragment();
        }
    } else if (newFragment == ScreenList.INITIALIZATION_DIALOG) {
        if (currentFragment == ScreenList.INITIALIZATION_DIALOG) {
            WebLogger.getLogger(getAppName()).e(t, "Unexpected: currentFragment == INITIALIZATION_DIALOG");
            return;
        } else {
            f = mgr.findFragmentById(InitializationFragment.ID);
            if (f == null) {
                f = new InitializationFragment();
            }
            ((InitializationFragment) f).setFragmentToShowNext(
                    (currentFragment == null) ? ScreenList.FORM_CHOOSER.name() : currentFragment.name());
        }
    } else if (newFragment == ScreenList.FORM_DELETER) {
        f = mgr.findFragmentById(FormDeleteListFragment.ID);
        if (f == null) {
            f = new FormDeleteListFragment();
        }
    } else if (newFragment == ScreenList.FORM_DOWNLOADER) {
        f = mgr.findFragmentById(FormDownloadListFragment.ID);
        if (f == null) {
            f = new FormDownloadListFragment();
        }
    } else if (newFragment == ScreenList.INSTANCE_UPLOADER_TABLE_CHOOSER) {
        f = mgr.findFragmentById(InstanceUploaderTableChooserListFragment.ID);
        if (f == null) {
            f = new InstanceUploaderTableChooserListFragment();
        }
    } else if (newFragment == ScreenList.INSTANCE_UPLOADER) {
        f = mgr.findFragmentById(InstanceUploaderListFragment.ID);
        if (f == null) {
            f = new InstanceUploaderListFragment();
        }
        ((InstanceUploaderListFragment) f).changeUploadTableId();
    } else if (newFragment == ScreenList.WEBKIT) {
        f = mgr.findFragmentById(WebViewFragment.ID);
        if (f == null) {
            f = new WebViewFragment();
        }
    } else if (newFragment == ScreenList.ABOUT_MENU) {
        f = mgr.findFragmentById(AboutMenuFragment.ID);
        if (f == null) {
            f = new AboutMenuFragment();
        }

    } else {
        throw new IllegalStateException("Unrecognized ScreenList type");
    }

    FrameLayout shadow = (FrameLayout) findViewById(R.id.shadow_content);
    View frags = findViewById(R.id.main_content);
    View wkt = findViewById(R.id.webkit_view);
    shadow.setVisibility(View.GONE);
    shadow.removeAllViews();
    if (newFragment == ScreenList.WEBKIT) {
        frags.setVisibility(View.GONE);
        wkt.setVisibility(View.VISIBLE);
        wkt.invalidate();
    } else {
        wkt.setVisibility(View.GONE);
        frags.setVisibility(View.VISIBLE);
    }

    currentFragment = newFragment;
    BackStackEntry entry = null;
    for (int i = 0; i < mgr.getBackStackEntryCount(); ++i) {
        BackStackEntry e = mgr.getBackStackEntryAt(i);
        if (e.getName().equals(currentFragment.name())) {
            entry = e;
            break;
        }
    }
    if (entry != null) {
        // flush backward, including the screen want to go back to
        mgr.popBackStackImmediate(currentFragment.name(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    // add transaction to show the screen we want
    FragmentTransaction trans = mgr.beginTransaction();
    trans.replace(R.id.main_content, f);
    trans.addToBackStack(currentFragment.name());
    trans.commit();

    // and see if we should re-initialize...
    if ((currentFragment != ScreenList.INITIALIZATION_DIALOG)
            && Survey.getInstance().shouldRunInitializationTask(getAppName())) {
        WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView -- calling clearRunInitializationTask");
        // and immediately clear the should-run flag...
        Survey.getInstance().clearRunInitializationTask(getAppName());
        // OK we should swap to the InitializationFragment view
        swapToFragmentView(ScreenList.INITIALIZATION_DIALOG);
    } else {
        levelSafeInvalidateOptionsMenu();
    }
}

From source file:org.path.episample.android.activities.MainMenuActivity.java

public void swapToFragmentView(ScreenList newFragment) {
    WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView: " + newFragment.toString());

    String get = PropertiesSingleton.getProperty("survey",
            AdminPreferencesActivity.KEY_TURN_ON_OFF_WIFI_AUTOMATICALLY);
    if (!(get != null && get.equalsIgnoreCase("false"))) {
        if (mWifiManager.isWifiEnabled() && mWifiManager.getWifiState() != WifiManager.WIFI_STATE_DISABLED) {
            mWifiManager.setWifiEnabled(false);
        }//from w w  w. j ava2 s.co  m
    }

    FragmentManager mgr = getFragmentManager();
    Fragment f;
    if (newFragment == ScreenList.MAIN_SCREEN) {
        throw new IllegalStateException("unexpected reference to generic main screen");
    } else if (newFragment == ScreenList.CUSTOM_VIEW) {
        WebLogger.getLogger(getAppName()).w(t,
                "swapToFragmentView: changing navigation to move to WebKit (was custom view)");
        f = mgr.findFragmentById(WebViewFragment.ID);
        if (f == null) {
            f = new WebViewFragment();
        }
        newFragment = ScreenList.WEBKIT;
    } else if (newFragment == ScreenList.MAIN_MENU) {
        f = mgr.findFragmentById(MainMenuFragment.ID);
        if (f == null) {
            f = new MainMenuFragment();
        }
    } else if (newFragment == ScreenList.COLLECT_MODULE) {
        f = mgr.findFragmentById(CollectFragment.ID);
        if (f == null) {
            f = new CollectFragment();
        }
    } else if (newFragment == ScreenList.SEND_RECEIVE_WIFI_DIRECT_MODULE) {
        f = mgr.findFragmentById(SendReceiveFragment.ID);
        if (f == null) {
            f = new SendReceiveFragment();
        }
    } /*else if (newFragment == ScreenList.SEND_RECEIVE_BLUETOOTH_MODULE) {
       f = mgr.findFragmentById(SendReceiveFragmentBT.ID);
       if (f == null) {
          f = new SendReceiveFragmentBT();
       }
      }*/ else if (newFragment == ScreenList.SELECT_MODULE) {
        f = mgr.findFragmentById(SelectFragment.ID);
        if (f == null) {
            f = new SelectFragment();
        }
    } else if (newFragment == ScreenList.NAVIGATE_MODULE) {
        f = mgr.findFragmentById(NavigateFragment.ID);
        if (f == null) {
            f = new NavigateFragment();
        }
    } else if (newFragment == ScreenList.RESTORE_MODULE) {
        f = mgr.findFragmentById(RestoreFragment.ID);
        if (f == null) {
            f = new RestoreFragment();
        }
    } else if (newFragment == ScreenList.EDIT_CENSUS_MODULE) {
        f = mgr.findFragmentById(EditCensusFragment.ID);
        if (f == null) {
            f = new EditCensusFragment();
        }
    } else if (newFragment == ScreenList.REMOVE_CENSUS_MODULE) {
        f = mgr.findFragmentById(RemoveCensusFragment.ID);
        if (f == null) {
            f = new RemoveCensusFragment();
        }
    } else if (newFragment == ScreenList.INVALIDATE_CENSUS_MODULE) {
        f = mgr.findFragmentById(InvalidateCensusFragment.ID);
        if (f == null) {
            f = new InvalidateCensusFragment();
        }
    } else if (newFragment == ScreenList.FORM_CHOOSER) {
        f = mgr.findFragmentById(FormChooserListFragment.ID);
        if (f == null) {
            f = new FormChooserListFragment();
        }
    } else if (newFragment == ScreenList.INITIALIZATION_DIALOG) {
        if (currentFragment == ScreenList.INITIALIZATION_DIALOG) {
            WebLogger.getLogger(getAppName()).e(t, "Unexpected: currentFragment == INITIALIZATION_DIALOG");
            return;
        } else {
            f = mgr.findFragmentById(InitializationFragment.ID);
            if (f == null) {
                f = new InitializationFragment();
            }
            ((InitializationFragment) f).setFragmentToShowNext(
                    (currentFragment == null) ? ScreenList.FORM_CHOOSER.name() : currentFragment.name());
        }
    } else if (newFragment == ScreenList.FORM_DELETER) {
        f = mgr.findFragmentById(FormDeleteListFragment.ID);
        if (f == null) {
            f = new FormDeleteListFragment();
        }
    } else if (newFragment == ScreenList.FORM_DOWNLOADER) {
        f = mgr.findFragmentById(FormDownloadListFragment.ID);
        if (f == null) {
            f = new FormDownloadListFragment();
        }
    } else if (newFragment == ScreenList.INSTANCE_UPLOADER_TABLE_CHOOSER) {
        f = mgr.findFragmentById(InstanceUploaderTableChooserListFragment.ID);
        if (f == null) {
            f = new InstanceUploaderTableChooserListFragment();
        }
    } else if (newFragment == ScreenList.INSTANCE_UPLOADER) {
        f = mgr.findFragmentById(InstanceUploaderListFragment.ID);
        if (f == null) {
            f = new InstanceUploaderListFragment();
        }
        ((InstanceUploaderListFragment) f).changeUploadTableId();
    } else if (newFragment == ScreenList.WEBKIT) {
        f = mgr.findFragmentById(WebViewFragment.ID);
        if (f == null) {
            f = new WebViewFragment();
        }
    } else if (newFragment == ScreenList.ABOUT_MENU) {
        f = mgr.findFragmentById(AboutMenuFragment.ID);
        if (f == null) {
            f = new AboutMenuFragment();
        }

    } else {
        throw new IllegalStateException("Unrecognized ScreenList type");
    }

    FrameLayout shadow = (FrameLayout) findViewById(R.id.shadow_content);
    View frags = findViewById(R.id.main_content);
    View wkt = findViewById(R.id.webkit_view);
    shadow.setVisibility(View.GONE);
    shadow.removeAllViews();
    if (newFragment == ScreenList.WEBKIT) {
        frags.setVisibility(View.GONE);
        wkt.setVisibility(View.VISIBLE);
        wkt.invalidate();
    } else {
        wkt.setVisibility(View.GONE);
        frags.setVisibility(View.VISIBLE);
    }

    currentFragment = newFragment;
    BackStackEntry entry = null;
    for (int i = 0; i < mgr.getBackStackEntryCount(); ++i) {
        BackStackEntry e = mgr.getBackStackEntryAt(i);
        if (e.getName().equals(currentFragment.name())) {
            entry = e;
            break;
        }
    }
    if (entry != null) {
        // flush backward, including the screen want to go back to
        mgr.popBackStackImmediate(currentFragment.name(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    // add transaction to show the screen we want
    FragmentTransaction trans = mgr.beginTransaction();
    trans.replace(R.id.main_content, f);
    trans.addToBackStack(currentFragment.name());
    trans.commit();

    // and see if we should re-initialize...
    if ((currentFragment != ScreenList.INITIALIZATION_DIALOG)
            && Survey.getInstance().shouldRunInitializationTask(getAppName())) {
        WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView -- calling clearRunInitializationTask");
        // and immediately clear the should-run flag...
        Survey.getInstance().clearRunInitializationTask(getAppName());
        // OK we should swap to the InitializationFragment view
        swapToFragmentView(ScreenList.INITIALIZATION_DIALOG);
    } else {
        levelSafeInvalidateOptionsMenu();
    }
}