Example usage for android.os Bundle putSerializable

List of usage examples for android.os Bundle putSerializable

Introduction

In this page you can find the example usage for android.os Bundle putSerializable.

Prototype

@Override
public void putSerializable(@Nullable String key, @Nullable Serializable value) 

Source Link

Document

Inserts a Serializable value into the mapping of this Bundle, replacing any existing value for the given key.

Usage

From source file:com.example.ray.firstapp.bottombar.BottomBar.java

/**
 * Call this method in your Activity's onSaveInstanceState
 * to keep the BottomBar's state on configuration change.
 *
 * @param outState the Bundle to save data to.
 *///from w  ww  .  ja  va  2s .  c o  m
public void onSaveInstanceState(Bundle outState) {
    outState.putInt(STATE_CURRENT_SELECTED_TAB, mCurrentTabPosition);

    if (mBadgeMap != null && mBadgeMap.size() > 0) {
        if (mBadgeStateMap == null) {
            mBadgeStateMap = new HashMap<>();
        }

        for (Integer key : mBadgeMap.keySet()) {
            BottomBarBadge badgeCandidate = (BottomBarBadge) mOuterContainer
                    .findViewWithTag(mBadgeMap.get(key));

            if (badgeCandidate != null) {
                mBadgeStateMap.put(key, badgeCandidate.isVisible());
            }
        }

        outState.putSerializable(STATE_BADGE_STATES_BUNDLE, mBadgeStateMap);
    }

    if (mFragmentManager != null && mFragmentContainer != 0 && mItems != null
            && mItems instanceof BottomBarFragment[]) {
        BottomBarFragment bottomBarFragment = (BottomBarFragment) mItems[mCurrentTabPosition];

        if (bottomBarFragment.getFragment() != null) {
            bottomBarFragment.getFragment().onSaveInstanceState(outState);
        } else if (bottomBarFragment.getSupportFragment() != null) {
            bottomBarFragment.getSupportFragment().onSaveInstanceState(outState);
        }
    }
}

From source file:com.jarklee.materialdatetimepicker.date.DatePickerDialog.java

@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(KEY_SELECTED_YEAR, mCalendar.get(Calendar.YEAR));
    outState.putInt(KEY_SELECTED_MONTH, mCalendar.get(Calendar.MONTH));
    outState.putInt(KEY_SELECTED_DAY, mCalendar.get(Calendar.DAY_OF_MONTH));
    outState.putInt(KEY_WEEK_START, mWeekStart);
    outState.putInt(KEY_YEAR_START, mMinYear);
    outState.putInt(KEY_YEAR_END, mMaxYear);
    outState.putInt(KEY_CURRENT_VIEW, mCurrentView);
    int listPosition = -1;
    if (mCurrentView == MONTH_AND_DAY_VIEW) {
        listPosition = mDayPickerView.getMostVisiblePosition();
    } else if (mCurrentView == YEAR_VIEW) {
        listPosition = mYearPickerView.getFirstVisiblePosition();
        outState.putInt(KEY_LIST_POSITION_OFFSET, mYearPickerView.getFirstPositionOffset());
    }//w ww  .  j  a  v  a 2  s . c o  m
    outState.putInt(KEY_LIST_POSITION, listPosition);
    outState.putSerializable(KEY_MIN_DATE, mMinDate);
    outState.putSerializable(KEY_MAX_DATE, mMaxDate);
    outState.putSerializable(KEY_HIGHLIGHTED_DAYS, highlightedDays);
    outState.putSerializable(KEY_SELECTABLE_DAYS, selectableDays);
    outState.putSerializable(KEY_DISABLED_DAYS, disabledDays);
    outState.putBoolean(KEY_THEME_DARK, mThemeDark);
    outState.putBoolean(KEY_THEME_DARK_CHANGED, mThemeDarkChanged);
    outState.putInt(KEY_ACCENT, mAccentColor);
    outState.putBoolean(KEY_VIBRATE, mVibrate);
    outState.putBoolean(KEY_DISMISS, mDismissOnPause);
    outState.putBoolean(KEY_AUTO_DISMISS, mAutoDismiss);
    outState.putInt(KEY_DEFAULT_VIEW, mDefaultView);
    outState.putString(KEY_TITLE, mTitle);
    outState.putInt(KEY_OK_RESID, mOkResid);
    outState.putString(KEY_OK_STRING, mOkString);
    outState.putInt(KEY_CANCEL_RESID, mCancelResid);
    outState.putString(KEY_CANCEL_STRING, mCancelString);
}

From source file:com.gelakinetic.mtgfam.activities.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /* http://stackoverflow.com/questions/13179620/force-overflow-menu-in-actionbarsherlock/13180285
     * //from  w w w  . j a v a  2  s . c  o m
     * Open ActionBarSherlock/src/com/actionbarsherlock/internal/view/menu/ActionMenuPresenter.java, go to method reserveOverflow
     * Replace the original with:
     * public static boolean reserveOverflow(Context context) { return true; }
     */
    if (DEVICE_VERSION >= DEVICE_HONEYCOMB) {
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            if (menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        } catch (Exception ex) {
            // Ignore
        }
    }

    mFragmentManager = getSupportFragmentManager();

    try {
        pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    } catch (NameNotFoundException e) {
        pInfo = null;
    }

    if (prefAdapter == null) {
        prefAdapter = new PreferencesAdapter(this);
    }

    int lastVersion = prefAdapter.getLastVersion();
    if (pInfo.versionCode != lastVersion) {
        // Clear the robospice cache on upgrade. This way, no cached values w/o foil prices will exist
        try {
            spiceManager.removeAllDataFromCache();
        } catch (NullPointerException e) {
            // eat it. tasty
        }
        showDialogFragment(CHANGELOGDIALOG);
        prefAdapter.setLastVersion(pInfo.versionCode);
        bounceMenu = lastVersion <= 15; //Only bounce if the last version is 1.8.1 or lower (or a fresh install) 
    }

    File mtr = new File(getFilesDir(), JudgesCornerFragment.MTR_LOCAL_FILE);
    File ipg = new File(getFilesDir(), JudgesCornerFragment.IPG_LOCAL_FILE);
    if (!mtr.exists()) {
        try {
            InputStream in = getResources().openRawResource(R.raw.mtr);
            FileOutputStream fos = new FileOutputStream(mtr);
            IOUtils.copy(in, fos);
        } catch (FileNotFoundException e) {
            Log.w("MainActivity", "MTR file could not be copied: " + e.getMessage());
        } catch (IOException e) {
            Log.w("MainActivity", "MTR file could not be copied: " + e.getMessage());
        }
    }
    if (!ipg.exists()) {
        try {
            InputStream in = getResources().openRawResource(R.raw.ipg);
            FileOutputStream fos = new FileOutputStream(ipg);
            IOUtils.copy(in, fos);
        } catch (FileNotFoundException e) {
            Log.w("MainActivity", "IPG file could not be copied: " + e.getMessage());
        } catch (IOException e) {
            Log.w("MainActivity", "IPG file could not be copied: " + e.getMessage());
        }
    }

    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setIcon(R.drawable.sliding_menu_icon);

    SlidingMenu slidingMenu = getSlidingMenu();
    slidingMenu.setBehindWidthRes(R.dimen.sliding_menu_width);
    slidingMenu.setBehindScrollScale(0.0f);
    slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
    slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
    slidingMenu.setShadowDrawable(R.drawable.sliding_menu_shadow);
    setSlidingActionBarEnabled(false);
    setBehindContentView(R.layout.fragment_menu);

    me = this;

    boolean autoupdate = prefAdapter.getAutoUpdate();
    if (autoupdate) {
        // Only update the banning list if it hasn't been updated recently
        long curTime = new Date().getTime();
        int updatefrequency = Integer.valueOf(prefAdapter.getUpdateFrequency());
        int lastLegalityUpdate = prefAdapter.getLastLegalityUpdate();
        // days to ms
        if (((curTime / 1000) - lastLegalityUpdate) > (updatefrequency * 24 * 60 * 60)) {
            startService(new Intent(this, DbUpdaterService.class));
        }
    }

    timerHandler = new Handler();
    registerReceiver(endTimeReceiver, new IntentFilter(RoundTimerFragment.RESULT_FILTER));
    registerReceiver(startTimeReceiver, new IntentFilter(RoundTimerService.START_FILTER));
    registerReceiver(cancelTimeReceiver, new IntentFilter(RoundTimerService.CANCEL_FILTER));

    updatingDisplay = false;
    timeShowing = false;

    getSlidingMenu().setOnOpenedListener(new OnOpenedListener() {

        @Override
        public void onOpened() {
            // Close the keyboard if the slidingMenu is opened
            hideKeyboard();
        }
    });

    setContentView(R.layout.fragment_activity);
    getSupportFragmentManager().beginTransaction().replace(R.id.frag_menu, new MenuFragment()).commit();

    showOnePane();
    if (findViewById(R.id.middle_container) != null) {
        // The detail container view will be present only in the
        // large-screen layouts (res/values-large and
        // res/values-sw600dp). If this view is present, then the
        // activity should be in two-pane mode.
        mIsATablet = true;
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mThreePane = true;
        } else {
            mThreePane = false;
        }
    } else {
        mThreePane = false;
        mIsATablet = false;
        if (findViewById(R.id.middle_container) != null) {
            findViewById(R.id.middle_container).setVisibility(View.GONE);
            findViewById(R.id.right_container).setVisibility(View.GONE);
        }
    }

    Intent intent = getIntent();

    if (savedInstanceState == null) {
        try {
            if (intent.getAction().equals(Intent.ACTION_VIEW)) { //apparently this can NPE on 4.3. because why not. if we catch it, launch the default frag
                // handles a click on a search suggestion; launches activity to show word
                Uri u = intent.getData();
                long id = Long.parseLong(u.getLastPathSegment());

                // add a fragment
                Bundle args = new Bundle();
                args.putBoolean("isSingle", true);
                args.putLong("id", id);
                CardViewFragment rlFrag = new CardViewFragment();
                rlFrag.setArguments(args);

                attachSingleFragment(rlFrag, "left_frag", false, false);
                showOnePane();
                hideKeyboard();
            } else if (intent.getAction().equals(Intent.ACTION_SEARCH)) {
                boolean consolidate = prefAdapter.getConsolidateSearch();
                String query = intent.getStringExtra(SearchManager.QUERY);
                SearchCriteria sc = new SearchCriteria();
                sc.Name = query;
                sc.Set_Logic = (consolidate ? CardDbAdapter.FIRSTPRINTING : CardDbAdapter.ALLPRINTINGS);

                // add a fragment
                Bundle args = new Bundle();
                args.putBoolean(SearchViewFragment.RANDOM, false);
                args.putSerializable(SearchViewFragment.CRITERIA, sc);
                if (mIsATablet) {
                    SearchViewFragment svFrag = new SearchViewFragment();
                    svFrag.setArguments(args);
                    attachSingleFragment(svFrag, "left_frag", false, false);
                } else {
                    ResultListFragment rlFrag = new ResultListFragment();
                    rlFrag.setArguments(args);
                    attachSingleFragment(rlFrag, "left_frag", false, false);
                }
                hideKeyboard();
            } else if (intent.getAction().equals(ACTION_FULL_SEARCH)) {
                attachSingleFragment(new SearchViewFragment(), "left_frag", false, false);
                showOnePane();
            } else if (intent.getAction().equals(ACTION_WIDGET_SEARCH)) {
                attachSingleFragment(new SearchWidgetFragment(), "left_frag", false, false);
                showOnePane();
            } else if (intent.getAction().equals(ACTION_ROUND_TIMER)) {
                attachSingleFragment(new RoundTimerFragment(), "left_frag", false, false);
                showOnePane();
            } else {
                launchDefaultFragment();
            }
        } catch (NullPointerException e) {
            launchDefaultFragment();
        }
    }
}

From source file:dev.memento.MainActivity.java

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    if (Log.LOG)/* ww w.  ja  va 2  s.  c  o m*/
        Log.d(LOG_TAG, "-- onSaveInstanceState");

    mWebview.saveState(outState);
    outState.putSerializable("mDateChosen", mDateChosen);
    outState.putSerializable("mDateDisplayed", mDateDisplayed);
    outState.putString("mCurrentUrl", mCurrentUrl);
    outState.putString("mOriginalUrl", mOriginalUrl);
    outState.putString("mPageTitle", mPageTitle);
    outState.putSerializable("mMementos", mMementos);
}

From source file:cgeo.geocaching.CacheListActivity.java

private void switchListById(final int id, @NonNull final AfterLoadAction action) {
    if (id < 0) {
        return;//from w w  w  .j  ava  2s  . c  om
    }

    final Bundle extras = new Bundle();
    extras.putSerializable(BUNDLE_ACTION_KEY, action);

    if (id == PseudoList.HISTORY_LIST.id) {
        type = CacheListType.HISTORY;
        getSupportLoaderManager().destroyLoader(CacheListType.OFFLINE.getLoaderId());
        currentLoader = (AbstractSearchLoader) getSupportLoaderManager()
                .restartLoader(CacheListType.HISTORY.getLoaderId(), extras, this);
    } else {
        if (id == PseudoList.ALL_LIST.id) {
            listId = id;
            title = res.getString(R.string.list_all_lists);
        } else {
            final StoredList list = DataStore.getList(id);
            listId = list.id;
            title = list.title;
        }
        type = CacheListType.OFFLINE;

        getSupportLoaderManager().destroyLoader(CacheListType.HISTORY.getLoaderId());
        extras.putAll(OfflineGeocacheListLoader.getBundleForList(listId));
        currentLoader = (OfflineGeocacheListLoader) getSupportLoaderManager()
                .restartLoader(CacheListType.OFFLINE.getLoaderId(), extras, this);

        Settings.setLastDisplayedList(listId);
    }

    initAdapter();

    showProgress(true);
    showFooterLoadingCaches();
    adapter.setSelectMode(false);
    invalidateOptionsMenuCompatible();
}

From source file:com.fsck.k9.activity.Accounts.java

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (mSelectedContextAccount != null) {
        outState.putString(SELECTED_CONTEXT_ACCOUNT, mSelectedContextAccount.getUuid());
    }/*from  w w w. jav a2s.  co  m*/
    outState.putSerializable(STATE_UNREAD_COUNT, mUnreadMessageCount);
    outState.putSerializable(ACCOUNT_STATS, accountStats);
}

From source file:com.vegnab.vegnab.MainVNActivity.java

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // save the current subplot arguments in case we need to re-create the activity
    outState.putLong(ARG_SUBPLOT_TYPE_ID, mSubplotTypeId);
    outState.putLong(ARG_VISIT_ID, mVisitId);
    outState.putBoolean(ARG_CONNECTION_REQUESTED, mConnectionRequested);
    outState.putSerializable(ARG_PH_EXISTING_SET, mExistingPhCodes);
    outState.putLong(ARG_PURCH_REC_ID, mNewPurcRecId);
}

From source file:com.fowlcorp.homebank4android.gui.AccountRecyclerAdapter.java

@Override
public void onBindViewHolder(final OperationViewHolder holder, final int position) {
    final Operation operation = listOperation.get(position);

    final Calendar myDate = Calendar.getInstance();
    myDate.clear();// w w  w .  j  a va  2 s  . c  om
    myDate.setTime(operation.getDate().getTime());
    final SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE);
    holder.getRootLayout().setOnClickListener(new OnClickListener() {

        @SuppressWarnings("unchecked")
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(activity.getApplicationContext(), DetailedCardActivity.class);
            Bundle bdl = new Bundle();
            try {

                bdl.putString("Date", df.format(myDate.getTime()));
            } catch (Exception e) {
            }
            try {
                bdl.putString("Category",
                        (operation.getCategory().getParent() == null ? ""
                                : operation.getCategory().getParent().getName() + ": ")
                                + operation.getCategory().getName());
            } catch (Exception e) {
            }
            try {
                bdl.putString("Payee", operation.getPayee().getName());
            } catch (Exception e) {
            }
            try {
                bdl.putString("Wording", operation.getWording());
            } catch (Exception e) {
            }
            try {
                bdl.putString("Amount", String.valueOf(Round.roundAmount(operation.getAmount())));
            } catch (Exception e) {
            }
            try {
                bdl.putInt("Type", operation.getPayMode());
            } catch (Exception e) {
            }
            //                try {
            //                    intent.putExtra("Info", operation.getInfo());
            //                } catch (Exception e) {
            //                }
            try {
                bdl.putBoolean("Reconciled", operation.isReconciled());
            } catch (Exception e) {
            }
            try {
                bdl.putBoolean("Remind", operation.isRemind());
            } catch (Exception e) {
            }
            try {
                Log.d("Debug", String.valueOf(operation.isSplit()));
                bdl.putBoolean("Split", operation.isSplit());
            } catch (Exception e) {
            }
            try {
                bdl.putSerializable("Couple", operation.getSplits());
            } catch (Exception e) {
                e.printStackTrace();
            }

            intent.putExtras(bdl);

            //            Pair datePair = Pair.create(holder.getDate(), "date");
            //            Pair categoryPair = Pair.create(holder.getCategory(), "category");
            //            Pair wordingPair = Pair.create(holder.getWording(), "wording");
            //            Pair payeePair = Pair.create(holder.getPayee(), "payee");
            //            Pair amountPair = Pair.create(holder.getAmount(), "amount");
            Pair<View, String> cardPair = Pair.create((View) holder.getCard(), "card");
            //            Pair iconPair = Pair.create(holder.getMode(), "icon");
            ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity,
                    cardPair);
            ActivityCompat.startActivity(activity, intent, options.toBundle());
            //activity.startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(activity).toBundle());
            //activity.startActivity(intent);
        }

    });

    try {
        holder.getDate().setText(activity.getString(R.string.Date) + " : " + df.format(myDate.getTime()));
    } catch (Exception e) {
    }
    try {
        holder.getPayee().setText(activity.getString(R.string.Payee) + " : " + operation.getPayee().getName());
    } catch (Exception e) {
    }
    try {
        holder.getWording().setText(activity.getString(R.string.Wording) + " : " + operation.getWording());
    } catch (Exception e) {
    }
    if (!operation.isSplit()) {
        holder.getSplitLinear().removeAllViews();
        holder.getUnSplitLinear().setVisibility(LinearLayout.VISIBLE);
        try {
            holder.getCategory()
                    .setText(activity.getString(R.string.Wording) + " : "
                            + (operation.getCategory().getParent() == null ? ""
                                    : operation.getCategory().getParent().getName() + ": ")
                            + operation.getCategory().getName());
        } catch (Exception e) {
        }

    } else {
        holder.getUnSplitLinear().setVisibility(LinearLayout.GONE);

        LinearLayout splitLayout = holder.getSplitLinear();
        splitLayout.removeAllViews();
        LayoutInflater inflater = activity.getLayoutInflater();
        for (Triplet subOp : operation.getSplits()) {
            View view = inflater.inflate(R.layout.split_layout, null);

            TextView category = (TextView) view.findViewById(R.id.splitLayout_category);
            TextView memo = (TextView) view.findViewById(R.id.splitLayout_memo);
            TextView amount = (TextView) view.findViewById(R.id.splitLayout_amount);
            //System.out.println(activity.getString(R.string.cardLayout_category) + " " + (subOp.getCategory().getParent() == null ? "" :subOp.getCategory().getParent().getName() + ": ") + subOp.getCategory().getName());
            category.setText(activity.getString(R.string.Category) + " : "
                    + (subOp.getCategory().getParent() == null ? ""
                            : subOp.getCategory().getParent().getName() + ": ")
                    + subOp.getCategory().getName());
            amount.setText(colorText(activity.getString(R.string.Amount) + " : ",
                    "" + Round.roundAmount(subOp.getAmount())));
            memo.setText(activity.getString(R.string.Category) + " : " + operation.getWording());
            splitLayout.addView(view);
        }
    }
    try {
        holder.getAmount().setText(colorText(activity.getString(R.string.Amount) + " : ",
                String.valueOf(Round.roundAmount(operation.getAmount()))));
    } catch (Exception e) {
    }
    try {
        holder.getBalance().setText(colorText(activity.getString(R.string.Balance) + " : ",
                String.valueOf(Round.roundAmount(operation.getBalanceAccount()))));
    } catch (Exception e) {
    }

    if (operation.isSplit()) {
        holder.getOption().setImageResource(R.drawable.split);
    } else if (operation.isRemind()) {
        holder.getOption().setImageResource(R.drawable.remind);
        holder.getCard().setCardBackgroundColor(Color.parseColor("#ffebee"));
    } else {
        holder.getOption().setImageDrawable(null);
    }

    if (!operation.isReconciled() && !operation.isRemind()) {
        holder.getCard().setCardBackgroundColor(Color.parseColor("#fff3e0"));
    } else if (operation.isReconciled()) {
        holder.getCard().setCardBackgroundColor(Color.parseColor("#ffffff"));
    }

    try {
        switch (operation.getPayMode()) {
        case PayMode.CREDIT_CARD:
            holder.getMode().setImageResource(R.drawable.mastercard);
            break;
        case PayMode.DEBIT_CARD:
            holder.getMode().setImageResource(R.drawable.card);
            break;
        case PayMode.CASH:
            holder.getMode().setImageResource(R.drawable.cash);
            break;
        case PayMode.TRANSFERT:
            holder.getMode().setImageResource(R.drawable.transfert);
            break;
        case PayMode.ELECTRONIC_PAYMENT:
            holder.getMode().setImageResource(R.drawable.nfc);
            break;
        case PayMode.CHEQUE:
            holder.getMode().setImageResource(R.drawable.cheque);
            break;
        default:
            holder.getMode().setImageDrawable(null);
            break;
        }
    } catch (Exception e) {
    }

}

From source file:com.juick.android.MainActivity.java

public void updateNavigation() {
    navigationItems = new ArrayList<NavigationItem>();

    List<MicroBlog> blogs = new ArrayList<MicroBlog>(microBlogs.values());
    Collections.<MicroBlog>sort(blogs, new Comparator<MicroBlog>() {
        @Override//from ww w.j  a  va 2s  .  c  o m
        public int compare(MicroBlog microBlog, MicroBlog microBlog2) {
            return microBlog.getPiority() - microBlog2.getPiority();
        }
    });
    for (MicroBlog blog : blogs) {
        blog.addNavigationSources(navigationItems, this);
    }
    navigationItems.add(new NavigationItem(NAVITEM_UNREAD, R.string.navigationUnread,
            R.drawable.navicon_juickadvanced, "msrcUnread") {
        @Override
        public void action() {
            final NavigationItem thisNi = this;
            final ProgressDialog pd = new ProgressDialog(MainActivity.this);
            pd.setIndeterminate(true);
            pd.setTitle(R.string.navigationUnread);
            pd.setCancelable(true);
            pd.show();
            UnreadSegmentsView.loadPeriods(MainActivity.this,
                    new Utils.Function<Void, ArrayList<DatabaseService.Period>>() {
                        @Override
                        public Void apply(ArrayList<DatabaseService.Period> periods) {
                            if (pd.isShowing()) {
                                pd.cancel();
                                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                final AlertDialog alerDialog;
                                if (periods.size() == 0) {
                                    alerDialog = builder.setTitle(getString(R.string.UnreadSegments))
                                            .setMessage(getString(R.string.YouHaveNotEnabledForUnreadSegments))
                                            .setCancelable(true)
                                            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialogInterface, int i) {
                                                    dialogInterface.dismiss();
                                                    restoreLastNavigationPosition();
                                                }
                                            }).create();
                                } else {
                                    UnreadSegmentsView unreadSegmentsView = new UnreadSegmentsView(
                                            MainActivity.this, periods);
                                    final int myIndex = navigationItems.indexOf(thisNi);
                                    alerDialog = builder.setTitle(getString(R.string.ChooseUnreadSegment))
                                            .setView(unreadSegmentsView).setCancelable(true)
                                            .setNegativeButton(android.R.string.cancel,
                                                    new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialogInterface,
                                                                int i) {
                                                            dialogInterface.dismiss();
                                                            restoreLastNavigationPosition();
                                                        }
                                                    })
                                            .create();
                                    unreadSegmentsView.setListener(new UnreadSegmentsView.PeriodListener() {
                                        @Override
                                        public void onPeriodClicked(DatabaseService.Period period) {
                                            alerDialog.dismiss();
                                            int beforeMid = period.beforeMid;
                                            Bundle args = new Bundle();
                                            args.putSerializable("messagesSource",
                                                    new UnreadSegmentMessagesSource(
                                                            getString(R.string.navigationUnread),
                                                            MainActivity.this, period));
                                            if (getSelectedNavigationIndex() != myIndex) {
                                                setSelectedNavigationItem(myIndex);
                                            }
                                            runDefaultFragmentWithBundle(args, thisNi);
                                        }
                                    });
                                }
                                alerDialog.show();
                                restyleChildrenOrWidget(alerDialog.getWindow().getDecorView());
                            }
                            return null;
                        }
                    });
            return;
        }
    });
    navigationItems.add(new NavigationItem(NAVITEM_SAVED, R.string.navigationSaved,
            R.drawable.navicon_juickadvanced, "msrcSaved") {
        @Override
        public void action() {
            final Bundle args = new Bundle();
            args.putSerializable("messagesSource", new SavedMessagesSource(MainActivity.this));
            runDefaultFragmentWithBundle(args, this);
        }
    });
    navigationItems.add(new NavigationItem(NAVITEM_RECENT_READ, R.string.navigationRecentlyOpened,
            R.drawable.navicon_juickadvanced, "msrcRecentOpen") {
        @Override
        public void action() {
            final Bundle args = new Bundle();
            args.putSerializable("messagesSource", new RecentlyOpenedMessagesSource(MainActivity.this));
            runDefaultFragmentWithBundle(args, this);
        }
    });
    navigationItems.add(new NavigationItem(NAVITEM_RECENT_WRITE, R.string.navigationRecentlyCommented,
            R.drawable.navicon_juickadvanced, "msrcRecentComment") {
        @Override
        public void action() {
            final Bundle args = new Bundle();
            args.putSerializable("messagesSource", new RecentlyCommentedMessagesSource(MainActivity.this));
            runDefaultFragmentWithBundle(args, this);
        }
    });
    navigationItems.add(new NavigationItem(NAVITEM_ALL_COMBINED, R.string.navigationAllCombined,
            R.drawable.navicon_juickadvanced, "msrcAllCombined") {
        @Override
        public void action() {
            final Bundle args = new Bundle();
            args.putSerializable("messagesSource",
                    new CombinedAllMessagesSource(MainActivity.this, "combined_all"));
            runDefaultFragmentWithBundle(args, this);
        }

        @Override
        public ArrayList<String> getMenuItems() {
            String s = getString(R.string.SelectSources);
            ArrayList<String> strings = new ArrayList<String>();
            strings.add(s);
            return strings;
        }

        @Override
        public void handleMenuAction(int which, String value) {
            switch (which) {
            case 0:
                selectSourcesForAllCombined();
                break;
            }
        }
    });
    navigationItems.add(new NavigationItem(NAVITEM_SUBS_COMBINED, R.string.navigationSubsCombined,
            R.drawable.navicon_juickadvanced, "msrcSubsCombined") {
        @Override
        public void action() {
            final NavigationItem thiz = this;
            new Thread("MessageSource Initializer") {
                @Override
                public void run() {
                    final Bundle args = new Bundle();
                    args.putSerializable("messagesSource",
                            new CombinedSubscriptionMessagesSource(MainActivity.this));
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            runDefaultFragmentWithBundle(args, thiz);
                        }

                    });
                }
            }.start();
            final Bundle args = new Bundle();
            runDefaultFragmentWithBundle(args, this);
        }

        @Override
        public ArrayList<String> getMenuItems() {
            String s = getString(R.string.SelectSources);
            ArrayList<String> strings = new ArrayList<String>();
            strings.add(s);
            return strings;
        }

        @Override
        public void handleMenuAction(int which, String value) {
            switch (which) {
            case 0:
                selectSourcesForAllSubs();
                break;
            }
        }
    });
    int index = 10000;
    final SharedPreferences sp_order = getSharedPreferences("messages_source_ordering", MODE_PRIVATE);
    for (NavigationItem navigationItem : navigationItems) {
        navigationItem.itemOrder = sp_order.getInt("order_" + navigationItem.id, -1);
        if (navigationItem.itemOrder == -1) {
            navigationItem.itemOrder = index;
            sp_order.edit().putInt("order_" + navigationItem.id, navigationItem.itemOrder).commit();
        }
        index++;
    }
    Collections.sort(navigationItems, new Comparator<NavigationItem>() {
        @Override
        public int compare(NavigationItem lhs, NavigationItem rhs) {
            return lhs.itemOrder - rhs.itemOrder; // increasing
        }
    });
    allNavigationItems = new ArrayList<NavigationItem>(navigationItems);
    final Iterator<NavigationItem> iterator = navigationItems.iterator();
    while (iterator.hasNext()) {
        NavigationItem next = iterator.next();
        if (next.sharedPrefsKey != null) {
            if (!sp.getBoolean(next.sharedPrefsKey, defaultValues(next.sharedPrefsKey))) {
                iterator.remove();
            }
        }
    }
    sp_order.edit().commit(); // save

    final boolean compressedMenu = sp.getBoolean("compressedMenu", false);
    float menuFontScale = 1;
    try {
        menuFontScale = Float.parseFloat(sp.getString("menuFontScale", "1.0"));
    } catch (Exception e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    final float finalMenuFontScale = menuFontScale;
    navigationList = (DragSortListView) findViewById(R.id.navigation_list);

    // adapter for old-style navigation
    final BaseAdapter navigationAdapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return navigationItems.size();
        }

        @Override
        public Object getItem(int position) {
            return navigationItems.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (position == -1) {
                // NOOK is funny
                return convertView;
            }
            final int screenHeight = getWindow().getWindowManager().getDefaultDisplay().getHeight();
            final int layoutId = R.layout.simple_list_item_1_mine;
            final PressableLinearLayout retval = convertView != null ? (PressableLinearLayout) convertView
                    : (PressableLinearLayout) getLayoutInflater().inflate(layoutId, null);
            TextView tv = (TextView) retval.findViewById(android.R.id.text1);
            if (parent instanceof Spinner) {
                tv.setTextSize(18 * finalMenuFontScale);
                tv.setEllipsize(TextUtils.TruncateAt.MARQUEE);
            } else {
                tv.setTextSize(22 * finalMenuFontScale);
            }
            tv.setText(getString(navigationItems.get(position).labelId));
            if (compressedMenu) {
                int minHeight = (int) ((screenHeight * 0.7) / getCount());
                tv.setMinHeight(minHeight);
                tv.setMinimumHeight(minHeight);
            }
            retval.setPressedListener(new PressableLinearLayout.PressedListener() {
                @Override
                public void onPressStateChanged(boolean selected) {
                    MainActivity.restyleChildrenOrWidget(retval, false);
                }

                @Override
                public void onSelectStateChanged(boolean selected) {
                    MainActivity.restyleChildrenOrWidget(retval, false);
                }
            });
            MainActivity.restyleChildrenOrWidget(retval, false);
            return retval;
        }
    };
    // adapter for new-style navigation
    final BaseAdapter navigationListAdapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return getItems().size();
        }

        private ArrayList<NavigationItem> getItems() {
            if (navigationList.isDragEnabled()) {
                return allNavigationItems;
            } else {
                return navigationItems;
            }
        }

        @Override
        public Object getItem(int position) {
            return getItems().get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        float textSize = -1;

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (position == -1) {
                // NOOK is funny
                return convertView;
            }
            if (textSize < 0) {
                View inflate = getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
                TextView text = (TextView) inflate.findViewById(android.R.id.text1);
                textSize = text.getTextSize();
            }
            final int layoutId = R.layout.navigation_list_item;
            final PressableLinearLayout retval = convertView != null ? (PressableLinearLayout) convertView
                    : (PressableLinearLayout) getLayoutInflater().inflate(layoutId, null);
            TextView tv = (TextView) retval.findViewById(android.R.id.text1);
            final ArrayList<NavigationItem> items = getItems();
            final NavigationItem theItem = items.get(position);
            tv.setText(getString(theItem.labelId));
            ImageButton menuButton = (ImageButton) retval.findViewById(R.id.menu_button);
            menuButton.setFocusable(false);
            ArrayList<String> menuItems = theItem.getMenuItems();
            menuButton.setVisibility(menuItems != null && menuItems.size() > 0 ? View.VISIBLE : View.GONE);
            menuButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    doNavigationItemMenu(theItem);
                }
            });
            ImageView iv = (ImageView) retval.findViewById(android.R.id.icon);
            iv.setImageResource(theItem.imageId);
            retval.findViewById(R.id.draggable)
                    .setVisibility(items != allNavigationItems ? View.GONE : View.VISIBLE);
            retval.findViewById(R.id.checkbox).setVisibility(
                    items != allNavigationItems || theItem.sharedPrefsKey == null ? View.GONE : View.VISIBLE);
            CheckBox cb = (CheckBox) retval.findViewById(R.id.checkbox);
            cb.setOnCheckedChangeListener(null);
            if (theItem.sharedPrefsKey != null) {
                cb.setChecked(sp.getBoolean(theItem.sharedPrefsKey, defaultValues(theItem.sharedPrefsKey)));
            }
            cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    sp.edit().putBoolean(theItem.sharedPrefsKey, isChecked).commit();
                }
            });
            int spacing = sp.getInt("navigation_spacing", 0);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize + spacing);

            retval.setPadding(0, spacing, 0, spacing);
            return retval;
        }
    };
    ActionBar bar = getSupportActionBar();
    updateActionBarMode();
    navigationList.setDragEnabled(false);
    ((DragSortController) navigationList.getFloatViewManager()).setDragHandleId(R.id.draggable);
    navigationList.setAdapter(navigationListAdapter);
    navigationList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
            setSelectedNavigationItem(position);
            closeNavigationMenu(true, false);
        }
    });
    navigationList.setDropListener(new DragSortListView.DropListener() {
        @Override
        public void drop(int from, int to) {
            final NavigationItem item = allNavigationItems.remove(from);
            allNavigationItems.add(to, item);

            int index = 0;
            for (NavigationItem allNavigationItem : allNavigationItems) {
                if (allNavigationItem.itemOrder != index) {
                    allNavigationItem.itemOrder = index;
                    sp_order.edit().putInt("order_" + allNavigationItem.id, allNavigationItem.itemOrder)
                            .commit();
                }
                index++;
            }
            sp_order.edit().commit(); // save
            navigationListAdapter.notifyDataSetChanged();
            //To change body of implemented methods use File | Settings | File Templates.
        }
    });
    bar.setListNavigationCallbacks(navigationAdapter, this);
    final View navigationMenuButton = (View) findViewById(R.id.navigation_menu_button);
    navigationMenuButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new AlertDialog.Builder(MainActivity.this)
                    .setItems(navigationList.isDragEnabled() ? R.array.navigation_menu_end
                            : R.array.navigation_menu_start, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    int spacing = sp.getInt("navigation_spacing", 0);
                                    switch (which) {
                                    case 0:
                                        if (navigationList.isDragEnabled()) {
                                            navigationList.setDragEnabled(false);
                                            updateNavigation();
                                        } else {
                                            navigationList.setDragEnabled(true);
                                        }
                                        break;
                                    case 1:
                                        final Map<String, ?> all = sp_order.getAll();
                                        for (String s : all.keySet()) {
                                            sp_order.edit().remove(s).commit();
                                        }
                                        sp_order.edit().commit();
                                        updateNavigation();
                                        break;
                                    case 2: // wider
                                        sp.edit().putInt("navigation_spacing", spacing + 1).commit();
                                        ((BaseAdapter) navigationList.getAdapter()).notifyDataSetInvalidated();
                                        break;
                                    case 3: // narrower
                                        if (spacing > 0) {
                                            sp.edit().putInt("navigation_spacing", spacing - 1).commit();
                                            ((BaseAdapter) navigationList.getAdapter())
                                                    .notifyDataSetInvalidated();
                                        }
                                        break;
                                    case 4: // logout from..
                                        logoutFromSomeServices();
                                        break;

                                    }
                                    navigationListAdapter.notifyDataSetChanged();
                                }
                            })
                    .setCancelable(true).create().show();
        }
    });

    final SharedPreferences spn = getSharedPreferences("saved_last_navigation_type", MODE_PRIVATE);
    int restoredLastNavItem = spn.getInt("last_navigation", 0);
    if (restoredLastNavItem != 0) {
        NavigationItem allSources = null;
        for (int i = 0; i < navigationItems.size(); i++) {
            NavigationItem navigationItem = navigationItems.get(i);
            if (navigationItem.labelId == restoredLastNavItem) {
                lastNavigationItem = navigationItem;
            }
            if (navigationItem.labelId == R.string.navigationAll) {
                allSources = navigationItem;
            }
        }
        if (lastNavigationItem == null) {
            lastNavigationItem = allSources; // could be null if not configured
        }
        if (lastNavigationItem == null && navigationItems.size() > 0) {
            lastNavigationItem = navigationItems.get(0); // last default
        }
        if (lastNavigationItem != null) {
            restoreLastNavigationPosition();
            lastNavigationItem.action();
        }
    }

}

From source file:com.free.searcher.MainFragment.java

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Log.i("SearcheFragment.onSaveInstanceState();", outState + ", " + actionBar.getTabCount());
    outState.putInt("level selected", actionBar.getSelectedNavigationIndex());
    outState.putStringArray("selectedFiles", selectedFiles);

    outState.putSerializable("files", files);

    outState.putString("currentZipFileName", currentZipFileName);
    if (extractFile != null) {
        extractFile.close();//from  w w  w .jav a 2s  . c  om
    }
    outState.putString("currentSearching", currentSearching);

    outState.putString("load", load);

    Log.d("load", load + " xxx");
    outState.putString("currentUrl", currentUrl);
    //      outState.putString("source", HtmlSourceViewJavaScriptInterface.source);
    outState.putCharSequence("query",
            (mSearchView != null && mSearchView.getQuery() != null) ? mSearchView.getQuery() : "");
    status = statusView.getText();
    outState.putCharSequence("status", status);

    locX = webView.getScrollX();
    outState.putInt("locX", locX);
    locY = webView.getScrollY();
    outState.putInt("locY", locY);

    outState.putString("home", home);

    webView.saveState((webViewBundle = new Bundle()));
    outState.putBundle("webViewBundle", webViewBundle);
    Log.d("frag.onSaveInstanceState();", outState + "");
    /**
     try {
     outState.putString("readTextFiles", Util.listToString(readTextFiles, false, ";;;"));
     outState.putString("initFolderFiles", Util.listToString(initFolderFiles, false, ";;;"));
     } catch (Throwable t) {
     t.printStackTrace();
     }
     **/
}