Example usage for android.os Bundle getSerializable

List of usage examples for android.os Bundle getSerializable

Introduction

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

Prototype

@Override
@Nullable
public Serializable getSerializable(@Nullable String key) 

Source Link

Document

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Usage

From source file:cgeo.geocaching.CacheListActivity.java

@Override
public Loader<SearchResult> onCreateLoader(final int type, final Bundle extras) {
    if (type >= CacheListLoaderType.values().length) {
        throw new IllegalArgumentException("invalid loader type " + type);
    }/*from  ww  w.  j  a v a  2 s  . c  o m*/
    final CacheListLoaderType enumType = CacheListLoaderType.values()[type];
    AbstractSearchLoader loader = null;
    switch (enumType) {
    case OFFLINE:
        // open either the requested or the last list
        if (extras.containsKey(Intents.EXTRA_LIST_ID)) {
            listId = extras.getInt(Intents.EXTRA_LIST_ID);
        } else {
            listId = Settings.getLastDisplayedList();
        }
        if (listId == PseudoList.ALL_LIST.id) {
            title = res.getString(R.string.list_all_lists);
        } else if (listId <= StoredList.TEMPORARY_LIST.id) {
            listId = StoredList.STANDARD_LIST_ID;
            title = res.getString(R.string.stored_caches_button);
        } else {
            final StoredList list = DataStore.getList(listId);
            // list.id may be different if listId was not valid
            if (list.id != listId) {
                showToast(getString(R.string.list_not_available));
            }
            listId = list.id;
            title = list.title;
        }

        loader = new OfflineGeocacheListLoader(this, coords, listId);

        break;
    case HISTORY:
        title = res.getString(R.string.caches_history);
        listId = PseudoList.HISTORY_LIST.id;
        loader = new HistoryGeocacheListLoader(this, coords);
        break;
    case NEAREST:
        title = res.getString(R.string.caches_nearby);
        loader = new CoordsGeocacheListLoader(this, coords);
        break;
    case COORDINATE:
        title = coords.toString();
        loader = new CoordsGeocacheListLoader(this, coords);
        break;
    case KEYWORD:
        final String keyword = extras.getString(Intents.EXTRA_KEYWORD);
        title = listNameMemento.rememberTerm(keyword);
        if (keyword != null) {
            loader = new KeywordGeocacheListLoader(this, keyword);
        }
        break;
    case ADDRESS:
        final String address = extras.getString(Intents.EXTRA_ADDRESS);
        if (StringUtils.isNotBlank(address)) {
            title = listNameMemento.rememberTerm(address);
        } else {
            title = coords.toString();
        }
        loader = new CoordsGeocacheListLoader(this, coords);
        break;
    case FINDER:
        final String username = extras.getString(Intents.EXTRA_USERNAME);
        title = listNameMemento.rememberTerm(username);
        if (username != null) {
            loader = new FinderGeocacheListLoader(this, username);
        }
        break;
    case OWNER:
        final String ownerName = extras.getString(Intents.EXTRA_USERNAME);
        title = listNameMemento.rememberTerm(ownerName);
        if (ownerName != null) {
            loader = new OwnerGeocacheListLoader(this, ownerName);
        }
        break;
    case MAP:
        //TODO Build Null loader
        title = res.getString(R.string.map_map);
        search = (SearchResult) extras.get(Intents.EXTRA_SEARCH);
        replaceCacheListFromSearch();
        loadCachesHandler.sendMessage(Message.obtain());
        break;
    case NEXT_PAGE:
        loader = new NextPageGeocacheListLoader(this, search);
        break;
    case POCKET:
        final String guid = extras.getString(Intents.EXTRA_POCKET_GUID);
        title = listNameMemento.rememberTerm(extras.getString(Intents.EXTRA_NAME));
        loader = new PocketGeocacheListLoader(this, guid);
        break;
    }
    // if there is a title given in the activity start request, use this one instead of the default
    if (extras != null && StringUtils.isNotBlank(extras.getString(Intents.EXTRA_TITLE))) {
        title = extras.getString(Intents.EXTRA_TITLE);
    }
    if (loader != null && extras != null && extras.getSerializable(BUNDLE_ACTION_KEY) != null) {
        final AfterLoadAction action = (AfterLoadAction) extras.getSerializable(BUNDLE_ACTION_KEY);
        loader.setAfterLoadAction(action);
    }
    updateTitle();
    showProgress(true);
    showFooterLoadingCaches();

    return loader;
}

From source file:com.klinker.android.launcher.launcher3.Launcher.java

/**
 * Restores the previous state, if it exists.
 *
 * @param savedState The previous state.
 *//*  w  w w  . j  a v a  2s  . com*/
@SuppressWarnings("unchecked")
private void restoreState(Bundle savedState) {
    if (savedState == null) {
        return;
    }

    State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
    if (state == State.APPS || state == State.WIDGETS) {
        mOnResumeState = state;
    }

    int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, PagedView.INVALID_RESTORE_PAGE);
    if (currentScreen != PagedView.INVALID_RESTORE_PAGE) {
        mWorkspace.setRestorePage(currentScreen);
    }

    final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1);
    final long pendingAddScreen = savedState.getLong(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);

    if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) {
        mPendingAddInfo.container = pendingAddContainer;
        mPendingAddInfo.screenId = pendingAddScreen;
        mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
        mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
        mPendingAddInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
        mPendingAddInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
        AppWidgetProviderInfo info = savedState.getParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO);
        mPendingAddWidgetInfo = info == null ? null
                : LauncherAppWidgetProviderInfo.fromProviderInfo(this, info);

        mPendingAddWidgetId = savedState.getInt(RUNTIME_STATE_PENDING_ADD_WIDGET_ID);
        setWaitingForResult(true);
        mRestoring = true;
    }

    mItemIdToViewId = (HashMap<Integer, Integer>) savedState.getSerializable(RUNTIME_STATE_VIEW_IDS);
}

From source file:com.tct.mail.compose.ComposeActivity.java

private void initAttachmentsFromIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    if (extras == null) {
        extras = Bundle.EMPTY;/*from w  ww  . j  av  a  2  s.  c o m*/
    }
    final String action = intent.getAction();
    if (!mAttachmentsChanged) {
        long totalSize = 0;
        if (extras.containsKey(EXTRA_ATTACHMENTS)) {
            String[] uris = (String[]) extras.getSerializable(EXTRA_ATTACHMENTS);
            for (String uriString : uris) {
                final Uri uri = Uri.parse(uriString);
                long size = 0;
                try {
                    if (handleSpecialAttachmentUri(uri)) {
                        continue;
                    }

                    final Attachment a = mAttachmentsView.generateLocalAttachment(uri);
                    //TS: rong-tang 2016-03-02 EMAIL BUGFIX-1712549 ADD_S
                    if (a == null) {
                        continue;
                    }
                    //TS: rong-tang 2016-03-02 EMAIL BUGFIX-1712549 ADD_E
                    size = mAttachmentsView.addAttachment(mAccount, a, true);//TS: yanhua.chen 2015-6-8 EMAIL CR_996908 MOD

                    Analytics.getInstance().sendEvent("send_intent_attachment",
                            Utils.normalizeMimeType(a.getContentType()), null, size);

                } catch (AttachmentFailureException e) {
                    LogUtils.e(LOG_TAG, e, "Error adding attachment");
                    showAttachmentTooBigToast(e.getErrorRes());
                }
                totalSize += size;
            }
        }
        if (extras.containsKey(Intent.EXTRA_STREAM)) {
            if (!PermissionUtil.checkAndRequestPermissionForResult(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    PermissionUtil.REQ_CODE_PERMISSION_ADD_ATTACHMENT)) {
                return;
            }
            if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
                final ArrayList<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
                ArrayList<Attachment> attachments = new ArrayList<Attachment>();
                for (Uri uri : uris) {
                    if (uri == null) {
                        continue;
                    }
                    try {
                        if (handleSpecialAttachmentUri(uri)) {
                            continue;
                        }

                        final Attachment a = mAttachmentsView.generateLocalAttachment(uri);
                        //TS: rong-tang 2016-03-02 EMAIL BUGFIX-1712549 ADD_S
                        if (a == null) {
                            continue;
                        }
                        //TS: rong-tang 2016-03-02 EMAIL BUGFIX-1712549 ADD_E
                        attachments.add(a);

                        Analytics.getInstance().sendEvent("send_intent_attachment",
                                Utils.normalizeMimeType(a.getContentType()), null, a.size);

                    } catch (AttachmentFailureException e) {
                        LogUtils.e(LOG_TAG, e, "Error adding attachment");
                        String maxSize = AttachmentUtils.convertToHumanReadableSize(getApplicationContext(),
                                mAccount.settings.getMaxAttachmentSize());
                        showErrorToast(getString(R.string.generic_attachment_problem, maxSize));
                    }
                }
                // TS: zhaotianyong 2015-05-08 EMAIL BUGFIX_988459 MOD_S
                totalSize += addAttachments(attachments, false);
                // TS: zhaotianyong 2015-05-08 EMAIL BUGFIX_988459 MOD_E
            } else {
                final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
                if (uri != null) {
                    long size = 0;
                    //[BUGFIX]-Modified-BEGIN by TCTNJ.wenlu.wu,12/03/2014,PR-857886
                    if (!handleSpecialAttachmentUri(uri)) {

                        new AsyncTask<Void, Void, Void>() {
                            @Override
                            protected Void doInBackground(Void... params) {
                                try {
                                    Attachment mAttachment = mAttachmentsView.generateLocalAttachment(uri);
                                    android.os.Message msg = new android.os.Message();
                                    msg.what = 1001;
                                    msg.obj = mAttachment;
                                    mHandler.sendMessage(msg);
                                } catch (AttachmentFailureException e) {
                                    LogUtils.e(LOG_TAG, e, "Error adding attachment");
                                    showAttachmentTooBigToast(e.getErrorRes());
                                }
                                return null;
                            }

                            @Override
                            protected void onPostExecute(Void result) {

                            }
                        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                    }
                    //[BUGFIX]-Modified-END by TCTNJ.wenlu.wu,12/03/2014,PR-857886

                    totalSize += size;
                }
            }
        }

        if (totalSize > 0) {
            mAttachmentsChanged = true;
            updateSaveUi();

            Analytics.getInstance().sendEvent("send_intent_with_attachments",
                    Integer.toString(getAttachments().size()), null, totalSize);
        }
    }
}

From source file:edu.usf.cutr.opentripplanner.android.fragments.MainFragment.java

private void restoreState(Bundle savedInstanceState) {
    if (savedInstanceState != null) {
        mMap = retrieveMap(mMap);//  w  w w .  j  a  v a2 s  .com

        if (!mMapFailed) {
            boolean mapFailedBefore = savedInstanceState.getBoolean(OTPApp.BUNDLE_KEY_MAP_FAILED);

            if (mapFailedBefore) {
                enableUIElements(true);

                initializeMapInterface(mMap);
            }

            if (!mapFailedBefore) {
                String overlayString = mPrefs.getString(OTPApp.PREFERENCE_KEY_MAP_TILE_SOURCE,
                        mApplicationContext.getResources().getString(R.string.map_tiles_default_server));
                updateOverlay(overlayString);
            }

            setTextBoxLocation(savedInstanceState.getString(OTPApp.BUNDLE_KEY_TB_START_LOCATION), true);
            setTextBoxLocation(savedInstanceState.getString(OTPApp.BUNDLE_KEY_TB_END_LOCATION), false);
            CameraPosition camPosition = savedInstanceState.getParcelable(OTPApp.BUNDLE_KEY_MAP_CAMERA);
            if (camPosition != null) {
                mMap.moveCamera(CameraUpdateFactory.newCameraPosition(camPosition));
            }

            if ((mStartMarkerPosition = savedInstanceState
                    .getParcelable(OTPApp.BUNDLE_KEY_MAP_START_MARKER_POSITION)) != null) {
                mStartMarker = addStartEndMarker(mStartMarkerPosition, true);
            }
            if ((mEndMarkerPosition = savedInstanceState
                    .getParcelable(OTPApp.BUNDLE_KEY_MAP_END_MARKER_POSITION)) != null) {
                mEndMarker = addStartEndMarker(mEndMarkerPosition, false);
            }

            mIsStartLocationGeocodingCompleted = savedInstanceState
                    .getBoolean(OTPApp.BUNDLE_KEY_IS_START_LOCATION_GEOCODING_PROCESSED);
            mIsEndLocationGeocodingCompleted = savedInstanceState
                    .getBoolean(OTPApp.BUNDLE_KEY_IS_END_LOCATION_GEOCODING_PROCESSED);
            mAppStarts = savedInstanceState.getBoolean(OTPApp.BUNDLE_KEY_APP_STARTS);
            mIsStartLocationChangedByUser = savedInstanceState
                    .getBoolean(OTPApp.BUNDLE_KEY_IS_START_LOCATION_CHANGED_BY_USER);
            mIsEndLocationChangedByUser = savedInstanceState
                    .getBoolean(OTPApp.BUNDLE_KEY_IS_END_LOCATION_CHANGED_BY_USER);

            mSavedLastLocation = savedInstanceState.getParcelable(OTPApp.BUNDLE_KEY_SAVED_LAST_LOCATION);
            mSavedLastLocationCheckedForServer = savedInstanceState
                    .getParcelable(OTPApp.BUNDLE_KEY_SAVED_LAST_LOCATION_CHECKED_FOR_SERVER);

            showBikeParameters(false);

            mDdlTravelMode.setItemChecked(savedInstanceState.getInt(OTPApp.BUNDLE_KEY_DDL_TRAVEL_MODE), true);
            TraverseModeSpinnerItem traverseModeSpinnerItem = (TraverseModeSpinnerItem) mDdlTravelMode
                    .getItemAtPosition(mDdlTravelMode.getCheckedItemPosition());
            if (traverseModeSpinnerItem != null) {
                // This should always be the case because if it's stored it was already checked
                if (traverseModeSpinnerItem.getTraverseModeSet().contains(TraverseMode.BICYCLE)) {
                    setBikeOptimizationAdapter(true);
                    mDdlOptimization.setItemChecked(
                            savedInstanceState.getInt(OTPApp.BUNDLE_KEY_DDL_OPTIMIZATION), true);
                    OptimizeSpinnerItem optimizeSpinnerItem = (OptimizeSpinnerItem) mDdlOptimization
                            .getItemAtPosition(mDdlOptimization.getCheckedItemPosition());
                    if (optimizeSpinnerItem != null) {
                        if (optimizeSpinnerItem.getOptimizeType().equals(OptimizeType.TRIANGLE)) {
                            showBikeParameters(true);
                        }
                    }
                }
            }
            mDdlTravelMode.setItemChecked(savedInstanceState.getInt(OTPApp.BUNDLE_KEY_DDL_TRAVEL_MODE), true);

            OTPBundle otpBundle = (OTPBundle) savedInstanceState.getSerializable(OTPApp.BUNDLE_KEY_OTP_BUNDLE);
            if (otpBundle != null) {
                List<Itinerary> itineraries = otpBundle.getItineraryList();
                getFragmentListener().onItinerariesLoaded(itineraries);
                getFragmentListener().onItinerarySelected(otpBundle.getCurrentItineraryIndex());
                fillItinerariesSpinner(itineraries);
            }
            showRouteOnMap(getFragmentListener().getCurrentItinerary(), false);

            Date savedTripDate = (Date) savedInstanceState.getSerializable(OTPApp.BUNDLE_KEY_TRIP_DATE);
            if (savedTripDate != null) {
                mTripDate = savedTripDate;
            }
            mArriveBy = savedInstanceState.getBoolean(OTPApp.BUNDLE_KEY_ARRIVE_BY, false);

            if (savedInstanceState.getString(OTPApp.BUNDLE_KEY_RESULT_TRIP_START_LOCATION) != null) {
                mResultTripStartLocation = savedInstanceState
                        .getString(OTPApp.BUNDLE_KEY_RESULT_TRIP_START_LOCATION);
            }
            if (savedInstanceState.getString(OTPApp.BUNDLE_KEY_RESULT_TRIP_END_LOCATION) != null) {
                mResultTripEndLocation = savedInstanceState
                        .getString(OTPApp.BUNDLE_KEY_RESULT_TRIP_END_LOCATION);
            }

            mBikeTriangleMinValue = savedInstanceState.getDouble(OTPApp.BUNDLE_KEY_SEEKBAR_MIN_VALUE);
            mBikeTriangleMaxValue = savedInstanceState.getDouble(OTPApp.BUNDLE_KEY_SEEKBAR_MAX_VALUE);
            mBikeTriangleParameters.setSelectedMinValue(mBikeTriangleMinValue);
            mBikeTriangleParameters.setSelectedMaxValue(mBikeTriangleMaxValue);

            mIsStartLocationChangedByUser = false;
            mIsEndLocationChangedByUser = false;
        }
    }
}

From source file:com.asksven.betterbatterystats.StatsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    super.onCreate(savedInstanceState);

    // HockeyApp//from   www.  j  av a  2  s.c  o  m
    try {
        MetricsManager.register(getApplication());
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }

    //Log.i(TAG, "OnCreated called");
    setContentView(R.layout.stats);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle(getString(R.string.app_name));

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayUseLogoEnabled(false);

    // set debugging
    if (sharedPrefs.getBoolean("debug_logging", false)) {
        LogSettings.DEBUG = true;
        CommonLogSettings.DEBUG = true;
    } else {
        LogSettings.DEBUG = false;
        CommonLogSettings.DEBUG = false;
    }

    swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);

    swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            doRefresh(true);
        }
    });

    ///////////////////////////////////////////////
    // check if we have a new release
    ///////////////////////////////////////////////
    // if yes do some migration (if required) and show release notes
    String strLastRelease = sharedPrefs.getString("last_release", "0");

    String strCurrentRelease = "";
    try {
        PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);

        strCurrentRelease = Integer.toString(pinfo.versionCode);
    } catch (Exception e) {
        // nop strCurrentRelease is set to ""
    }

    // Grant permissions if they are missing and root is available
    if (!SysUtils.hasBatteryStatsPermission(this) || !SysUtils.hasDumpsysPermission(this)
            || !SysUtils.hasPackageUsageStatsPermission(this)) {
        if ((RootShell.getInstance().isRooted())) {

            // attempt to set perms using pm-comand
            Log.i(TAG, "attempting to grant perms with 'pm grant'");

            String pkg = this.getPackageName();
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.BATTERY_STATS");
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.DUMP");
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.PACKAGE_USAGE_STATS");

            if (SysUtils.hasBatteryStatsPermission(this)) {
                Log.i(TAG, "succeeded");
            } else {
                Log.i(TAG, "failed");
            }
        }
    }

    // Package usage stats were introduced in SDK21 so we need to make the distinction
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // show install as system app screen if root available but perms missing
        if (!SysUtils.hasBatteryStatsPermission(this) || !SysUtils.hasDumpsysPermission(this)
                || !SysUtils.hasPackageUsageStatsPermission(this)) {
            Intent intentSystemApp = new Intent(this, SystemAppActivity.class);
            this.startActivity(intentSystemApp);
        }
    } else {
        if (!SysUtils.hasBatteryStatsPermission(this) || !SysUtils.hasDumpsysPermission(this)) {
            Intent intentSystemApp = new Intent(this, SystemAppActivity.class);
            this.startActivity(intentSystemApp);
        }

    }
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // first start
    if (strLastRelease.equals("0")) {

        boolean firstLaunch = !prefs.getBoolean("launched", false);

        if (firstLaunch) {
            // Save that the app has been launched
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("launched", true);
            editor.commit();

            // start service to persist reference
            Intent serviceIntent = new Intent(this, WriteUnpluggedReferenceService.class);
            this.startService(serviceIntent);

            // refresh widgets
            Intent intentRefreshWidgets = new Intent(LargeWidgetProvider.WIDGET_UPDATE);
            this.sendBroadcast(intentRefreshWidgets);

        }

        SharedPreferences.Editor updater = sharedPrefs.edit();
        updater.putString("last_release", strCurrentRelease);
        updater.commit();
    } else if (!strLastRelease.equals(strCurrentRelease)) {
        // save the current release to properties so that the dialog won't be shown till next version
        SharedPreferences.Editor updater = sharedPrefs.edit();
        updater.putString("last_release", strCurrentRelease);
        updater.commit();

        // we don't need to delete refs as long as we don't change the database schema
        //         Toast.makeText(this, getString(R.string.info_deleting_refs), Toast.LENGTH_SHORT).show();
        //         ReferenceStore.deleteAllRefs(this);
        //         Intent i = new Intent(this, WriteBootReferenceService.class);
        //         this.startService(i);
        //         i = new Intent(this, WriteUnpluggedReferenceService.class);
        //         this.startService(i);
        ChangeLog cl = new ChangeLog(this);
        cl.getLogDialog().show();

    }

    ///////////////////////////////////////////////
    // retrieve default selections for spinners
    // if none were passed
    ///////////////////////////////////////////////

    m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
    m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);

    if (!ReferenceStore.hasReferenceByName(m_refFromName, this)) {

        m_refFromName = Reference.BOOT_REF_FILENAME;
        Toast.makeText(this, getString(R.string.info_fallback_to_boot), Toast.LENGTH_SHORT).show();
    }

    if (LogSettings.DEBUG)
        Log.i(TAG, "onCreate state from preferences: refFrom=" + m_refFromName + " refTo=" + m_refToName);

    try {
        // recover any saved state
        if ((savedInstanceState != null) && (!savedInstanceState.isEmpty())) {
            m_iStat = (Integer) savedInstanceState.getSerializable("stat");
            m_refFromName = (String) savedInstanceState.getSerializable("stattypeFrom");
            m_refToName = (String) savedInstanceState.getSerializable("stattypeTo");

            if (LogSettings.DEBUG)
                Log.i(TAG,
                        "onCreate retrieved saved state: refFrom=" + m_refFromName + " refTo=" + m_refToName);

        }
    } catch (Exception e) {
        m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
        m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);

        Log.e(TAG, "Exception: " + e.getMessage());
        DataStorage.LogToFile(LOGFILE, "Exception in onCreate restoring Bundle");
        DataStorage.LogToFile(LOGFILE, e.getMessage());
        DataStorage.LogToFile(LOGFILE, e.getStackTrace());

        Toast.makeText(this, getString(R.string.info_state_recovery_error), Toast.LENGTH_SHORT).show();
    }

    // Handle the case the Activity was called from an intent with paramaters
    Bundle extras = getIntent().getExtras();
    if ((extras != null) && !extras.isEmpty()) {
        // Override if some values were passed to the intent
        if (extras.containsKey(StatsActivity.STAT))
            m_iStat = extras.getInt(StatsActivity.STAT);
        if (extras.containsKey(StatsActivity.STAT_TYPE_FROM))
            m_refFromName = extras.getString(StatsActivity.STAT_TYPE_FROM);
        if (extras.containsKey(StatsActivity.STAT_TYPE_TO))
            m_refToName = extras.getString(StatsActivity.STAT_TYPE_TO);

        if (LogSettings.DEBUG)
            Log.i(TAG, "onCreate state from extra: refFrom=" + m_refFromName + " refTo=" + m_refToName);

        boolean bCalledFromNotification = extras.getBoolean(StatsActivity.FROM_NOTIFICATION, false);

        // Clear the notifications that was clicked to call the activity
        if (bCalledFromNotification) {
            NotificationManager nM = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
            nM.cancel(EventWatcherService.NOTFICATION_ID);
        }
    }

    // Spinner for selecting the stat
    Spinner spinnerStat = (Spinner) findViewById(R.id.spinnerStat);

    ArrayAdapter spinnerStatAdapter = ArrayAdapter.createFromResource(this, R.array.stats,
            R.layout.bbs_spinner_layout); //android.R.layout.simple_spinner_item);
    spinnerStatAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item); // android.R.layout.simple_spinner_dropdown_item);

    spinnerStat.setAdapter(spinnerStatAdapter);
    // setSelection MUST be called after setAdapter
    spinnerStat.setSelection(m_iStat);
    spinnerStat.setOnItemSelectedListener(this);

    ///////////////////////////////////////////////
    // Spinner for Selecting the Stat type
    ///////////////////////////////////////////////
    Spinner spinnerStatType = (Spinner) findViewById(R.id.spinnerStatType);
    m_spinnerFromAdapter = new ReferencesAdapter(this, R.layout.bbs_spinner_layout); //android.R.layout.simple_spinner_item);
    m_spinnerFromAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item); //android.R.layout.simple_spinner_dropdown_item);
    spinnerStatType.setAdapter(m_spinnerFromAdapter);

    try {
        this.setListViewAdapter();
    } catch (BatteryInfoUnavailableException e) {
        Log.e(TAG, "Exception: " + Log.getStackTraceString(e));
        Snackbar.make(findViewById(android.R.id.content), R.string.info_service_connection_error,
                Snackbar.LENGTH_LONG).show();
        //         Toast.makeText(this,
        //               getString(R.string.info_service_connection_error),
        //               Toast.LENGTH_LONG).show();

    } catch (Exception e) {
        //Log.e(TAG, e.getMessage(), e.fillInStackTrace());
        Log.e(TAG, "Exception: " + Log.getStackTraceString(e));
        Toast.makeText(this, getString(R.string.info_unknown_stat_error), Toast.LENGTH_LONG).show();
    }
    // setSelection MUST be called after setAdapter
    spinnerStatType.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName));
    spinnerStatType.setOnItemSelectedListener(this);

    ///////////////////////////////////////////////
    // Spinner for Selecting the end sample
    ///////////////////////////////////////////////
    Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
    m_spinnerToAdapter = new ReferencesAdapter(this, R.layout.bbs_spinner_layout); //android.R.layout.simple_spinner_item);
    m_spinnerToAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item); //android.R.layout.simple_spinner_dropdown_item);

    spinnerStatSampleEnd.setVisibility(View.VISIBLE);
    spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
    // setSelection must be called after setAdapter
    if ((m_refToName != null) && !m_refToName.equals("")) {
        int pos = m_spinnerToAdapter.getPosition(m_refToName);
        spinnerStatSampleEnd.setSelection(pos);

    } else {
        spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
    }

    spinnerStatSampleEnd.setOnItemSelectedListener(this);

    ///////////////////////////////////////////////
    // sorting
    ///////////////////////////////////////////////
    m_iSorting = 0;

    // log reference store
    ReferenceStore.logReferences(this);

    if (LogSettings.DEBUG) {
        Log.i(TAG, "onCreate final state: refFrom=" + m_refFromName + " refTo=" + m_refToName);
        Log.i(TAG, "OnCreated end");
    }

}

From source file:com.amsterdam.marktbureau.makkelijkemarkt.DagvergunningFragment.java

/**
 * Get data retrieved with the intent, or restore state
 * @param savedInstanceState the previously saved state
 *//*  w  w  w.j a  va  2  s. co m*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // initialize the producten & vaste producten values
    String[] productParams = getResources().getStringArray(R.array.array_product_param);
    for (String product : productParams) {
        mProducten.put(product, -1);
        mProductenVast.put(product, -1);
    }

    // get settings from the shared preferences
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext());
    mMarktId = settings.getInt(getString(R.string.sharedpreferences_key_markt_id), 0);
    mActiveAccountId = settings.getInt(getString(R.string.sharedpreferences_key_account_id), 0);
    mActiveAccountNaam = settings.getString(getString(R.string.sharedpreferences_key_account_naam), null);

    // get the date of today for the dag param
    SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag));
    mDagToday = sdf.format(new Date());

    // only on fragment creation, not on rotation/re-creation
    if (savedInstanceState == null) {

        // check if we are editing an existing dagvergunning or making a new one
        Intent intent = getActivity().getIntent();
        if ((intent != null) && (intent.hasExtra(
                MakkelijkeMarktProvider.mTableDagvergunning + MakkelijkeMarktProvider.Dagvergunning.COL_ID))) {
            int dagvergunningId = intent.getIntExtra(
                    MakkelijkeMarktProvider.mTableDagvergunning + MakkelijkeMarktProvider.Dagvergunning.COL_ID,
                    0);

            if (dagvergunningId != 0) {
                mId = dagvergunningId;
            }
        }

        // init loader if an existing dagvergunning was selected
        if (mId > 0) {

            // create an argument bundle with the dagvergunning id and initialize the loader
            Bundle args = new Bundle();
            args.putInt(MakkelijkeMarktProvider.Dagvergunning.COL_ID, mId);
            getLoaderManager().initLoader(DAGVERGUNNING_LOADER, args, this);

            // show the progressbar (because we are fetching the koopman from the api later in the onloadfinished)
            mProgressbar.setVisibility(View.VISIBLE);
        } else {

            // check time in hours since last fetched the sollicitaties for selected markt
            long diffInHours = getResources()
                    .getInteger(R.integer.makkelijkemarkt_api_sollicitaties_fetch_interval_hours);
            if (settings
                    .contains(getContext().getString(R.string.sharedpreferences_key_sollicitaties_last_fetched)
                            + mMarktId)) {
                long lastFetchTimestamp = settings.getLong(
                        getContext().getString(R.string.sharedpreferences_key_sollicitaties_last_fetched)
                                + mMarktId,
                        0);
                long differenceMs = new Date().getTime() - lastFetchTimestamp;
                diffInHours = TimeUnit.MILLISECONDS.toHours(differenceMs);
            }

            // if last sollicitaties fetched more than 12 hours ago, fetch them again
            if (diffInHours >= getResources()
                    .getInteger(R.integer.makkelijkemarkt_api_sollicitaties_fetch_interval_hours)) {

                // show progress dialog
                mGetSollicitatiesProcessDialog.show();
                ApiGetSollicitaties getSollicitaties = new ApiGetSollicitaties(getContext());
                getSollicitaties.setMarktId(mMarktId);
                getSollicitaties.enqueue();
            }
        }
    } else {

        // restore dagvergunning data from saved state
        mMarktId = savedInstanceState.getInt(MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID);
        mDag = savedInstanceState.getString(MakkelijkeMarktProvider.Dagvergunning.COL_DAG);
        mId = savedInstanceState.getInt(MakkelijkeMarktProvider.Dagvergunning.COL_ID);
        mErkenningsnummer = savedInstanceState
                .getString(MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE);
        mErkenningsnummerInvoerMethode = savedInstanceState
                .getString(MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_METHODE);
        mRegistratieDatumtijd = savedInstanceState
                .getString(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_DATUMTIJD);
        mRegistratieGeolocatieLatitude = savedInstanceState
                .getDouble(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_GEOLOCATIE_LAT);
        mRegistratieGeolocatieLongitude = savedInstanceState
                .getDouble(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_GEOLOCATIE_LONG);
        mTotaleLengte = savedInstanceState.getInt(MakkelijkeMarktProvider.Dagvergunning.COL_TOTALE_LENGTE);
        mSollicitatieStatus = savedInstanceState
                .getString(MakkelijkeMarktProvider.Dagvergunning.COL_STATUS_SOLLICITATIE);
        mKoopmanAanwezig = savedInstanceState.getString(MakkelijkeMarktProvider.Dagvergunning.COL_AANWEZIG);
        mKoopmanId = savedInstanceState.getInt(MakkelijkeMarktProvider.Dagvergunning.COL_KOOPMAN_ID);
        mKoopmanVoorletters = savedInstanceState.getString(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS);
        mKoopmanAchternaam = savedInstanceState.getString(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM);
        mKoopmanFoto = savedInstanceState.getString(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL);
        mRegistratieAccountId = savedInstanceState
                .getInt(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_ACCOUNT_ID);
        mRegistratieAccountNaam = savedInstanceState.getString(MakkelijkeMarktProvider.Account.COL_NAAM);
        mSollicitatieId = savedInstanceState.getInt(MakkelijkeMarktProvider.Dagvergunning.COL_SOLLICITATIE_ID);
        mSollicitatieNummer = savedInstanceState
                .getInt(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER);
        mNotitie = savedInstanceState.getString(MakkelijkeMarktProvider.Dagvergunning.COL_NOTITIE);
        mProducten = (HashMap<String, Integer>) savedInstanceState.getSerializable(STATE_BUNDLE_KEY_PRODUCTS);
        mProductenVast = (HashMap<String, Integer>) savedInstanceState
                .getSerializable(STATE_BUNDLE_KEY_PRODUCTS_VAST);
        mVervangerId = savedInstanceState.getInt(MakkelijkeMarktProvider.Dagvergunning.COL_VERVANGER_ID);
        mVervangerErkenningsnummer = savedInstanceState
                .getString(MakkelijkeMarktProvider.Dagvergunning.COL_VERVANGER_ERKENNINGSNUMMER);

        // select tab of viewpager from saved fragment state (if it's different)
        if (mViewPager.getCurrentItem() != mCurrentTab) {
            mViewPager.setCurrentItem(mCurrentTab);
        }
    }

    // set the right wizard menu depending on the current tab position
    setWizardMenu(mCurrentTab);

    // prevent the keyboard from popping up on first pager fragment load
    Utility.hideKeyboard(getActivity());

    //        // TODO: get credentials and payleven api-key from mm api
    //        // decrypt loaded credentials
    //        String paylevenMerchantEmail = "marco@langebeeke.com";
    //        String paylevenMerchantPassword = "unknown";
    //        String paylevenApiKey = "unknown";
    //
    //        // register with payleven api
    //        PaylevenFactory.registerAsync(
    //                getContext(),
    //                paylevenMerchantEmail,
    //                paylevenMerchantPassword,
    //                paylevenApiKey,
    //                new PaylevenRegistrationListener() {
    //                    @Override
    //                    public void onRegistered(Payleven payleven) {
    //                        mPaylevenApi = payleven;
    //                        Utility.log(getContext(), LOG_TAG, "Payleven Registered!");
    //                    }
    //                    @Override
    //                    public void onError(PaylevenError error) {
    //                        Utility.log(getContext(), LOG_TAG, "Payleven registration Error: " + error.getMessage());
    //                    }
    //                });

    // TODO: in the overzicht step change 'Opslaan' into 'Afrekenen' and show a payment dialog when clicked
    // TODO: if the bluetooth payleven cardreader has not been paired yet inform the toezichthouder, show instructions and open the bluetooth settings
    // TODO: give the toezichthouder the option in the payment dialog to save without payleven and make the payment with an old pin device?
    // TODO: the payment dialog shows:
    // - logo's of the accepted debit card standards
    // - total amount to pay
    //      (this can be the difference between a changed dagvergunning and an already paid amount,
    //      or the total amount if it is a new dagvergunning. we don't pay refunds using the app?
    //      refunds can be done by the beheerder using the dashboard?
    //      or do we allow refunds in the app? In that case we need to inform the toezichthouder
    //      that a refund will be made, and keep him informed about the status of the trasnaction)
    // - 'start payment/refund' button?
    // - instructions for making the payment using the payleven cardreader
    // - optionally a selection list to select the bluetooth cardreader if it was not yet selected before
    //      (if it was already selected before, show the selected reader with a 'wiebertje' in front. when
    //      clicked it will show the list of cardreaders that can be selected)
    // - status of the transaction
    // TODO: when the payment is done succesfully we safe the dagvergunning and close the dialog and the dagvergunning activity
}

From source file:com.scooter1556.sms.android.activity.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Retrieve preferences if they exist
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPreferences.registerOnSharedPreferenceChangeListener(onPreferencesChanged);

    // Set volume control to media
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    // Initialise database
    db = new ConnectionDatabase(this);

    // Load default settings
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    // Action Bar
    assert getSupportActionBar() != null;
    getSupportActionBar().setDisplayShowHomeEnabled(false);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Navigation Drawer
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerList = (ListView) findViewById(R.id.navigation_drawer_list);

    NavigationDrawerListItem[] drawerListItems = new NavigationDrawerListItem[3];
    drawerListItems[MENU_MEDIA_BROWSER] = new NavigationDrawerListItem(R.drawable.ic_media_browser,
            getResources().getStringArray(R.array.navigation_drawer_list_items)[MENU_MEDIA_BROWSER]);
    drawerListItems[MENU_SETTINGS] = new NavigationDrawerListItem(R.drawable.ic_settings,
            getResources().getStringArray(R.array.navigation_drawer_list_items)[MENU_SETTINGS]);
    drawerListItems[MENU_EXIT] = new NavigationDrawerListItem(R.drawable.ic_close,
            getResources().getStringArray(R.array.navigation_drawer_list_items)[MENU_EXIT]);
    NavigationDrawerListItemAdapter drawerAdapter = new NavigationDrawerListItemAdapter(this,
            R.layout.drawer_list_item, drawerListItems);
    drawerList.setAdapter(drawerAdapter);
    drawerList.setOnItemClickListener(new DrawerItemClickListener());

    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.navigation_drawer_open,
            R.string.navigation_drawer_close) {

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            getSupportActionBar().setTitle(title);
        }// w  ww.  jav  a 2  s.  c om

        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            title = getSupportActionBar().getTitle().toString();
            getSupportActionBar().setTitle(getString(R.string.navigation_drawer_title));
        }
    };

    // Set the drawer toggle as the DrawerListener
    drawerLayout.setDrawerListener(drawerToggle);

    // Sliding Panel
    slidingPanel = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
    slidingPanel.setPanelHeight((int) getResources().getDimension(R.dimen.audio_player_small_fragment_height));

    PanelSlideListener slidingPanelListener = new SlidingUpPanelLayout.PanelSlideListener() {
        @Override
        public void onPanelAnchored(final View panel) {
        }

        @Override
        public void onPanelCollapsed(final View panel) {
            View audioPlayerSmallContainer = findViewById(R.id.sliding_panel_small_container);
            View audioPlayerContainer = findViewById(R.id.sliding_panel_container);
            audioPlayerSmallContainer.setVisibility(View.VISIBLE);
            audioPlayerSmallContainer.setAlpha(1.0f);
            audioPlayerContainer.setVisibility(View.GONE);
            audioPlayerContainer.setAlpha(1.0f);

            // Update menu items
            audioPlayerFragment.setMenuVisibility(false);
            audioPlaylistFragment.setMenuVisibility(false);
            mediaBrowserFragment.setMenuVisibility(true);

            //Update action bar title
            getSupportActionBar().setTitle(title);
        }

        @Override
        public void onPanelExpanded(final View panel) {
            View audioPlayerSmallContainer = findViewById(R.id.sliding_panel_small_container);
            View audioPlayerContainer = findViewById(R.id.sliding_panel_container);
            audioPlayerSmallContainer.setVisibility(View.GONE);
            audioPlayerSmallContainer.setAlpha(1.0f);
            audioPlayerContainer.setVisibility(View.VISIBLE);
            audioPlayerContainer.setAlpha(1.0f);

            // Update menu items
            audioPlayerFragment.setMenuVisibility(slidingPanelFragment == SLIDING_PANEL_PLAYER);
            audioPlaylistFragment.setMenuVisibility(slidingPanelFragment == SLIDING_PANEL_PLAYLIST);
            mediaBrowserFragment.setMenuVisibility(false);

            //Update action bar title
            getSupportActionBar().setTitle(slidingPanelTitle);
        }

        @Override
        public void onPanelHidden(final View view) {
        }

        @Override
        public void onPanelSlide(final View panel, final float slideOffset) {
            View audioPlayerSmallContainer = findViewById(R.id.sliding_panel_small_container);
            View audioPlayerContainer = findViewById(R.id.sliding_panel_container);

            if (slideOffset < 1.0f) {
                audioPlayerSmallContainer.setVisibility(View.VISIBLE);
                audioPlayerContainer.setVisibility(View.VISIBLE);
            } else {
                audioPlayerSmallContainer.setVisibility(View.GONE);
                audioPlayerContainer.setVisibility(View.VISIBLE);
            }

            audioPlayerSmallContainer.setAlpha(1.0f - slideOffset);
            audioPlayerContainer.setAlpha(slideOffset);
        }
    };

    slidingPanel.setPanelSlideListener(slidingPanelListener);

    if (savedInstanceState == null) {
        // Initialise main view
        mediaBrowserFragment = new MediaFolderFragment();
        mediaBrowserTitle = title = getString(R.string.media_title);
        getSupportFragmentManager().beginTransaction()
                .add(R.id.main_container, mediaBrowserFragment, Integer.toString(MENU_MEDIA_BROWSER)).commit();
        assert getSupportActionBar() != null;
        getSupportActionBar().setTitle(getString(R.string.media_title));
        updateDrawer(MENU_MEDIA_BROWSER);

        // Initialise small audio player sliding panel fragment
        audioPlayerSmallFragment = new AudioPlayerSmallFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.sliding_panel_small_container,
                audioPlayerSmallFragment, Integer.toString(SLIDING_PANEL_SMALL_PLAYER)).commit();

        // Initialise audio player fragment
        audioPlayerFragment = new AudioPlayerFragment();
        audioPlayerFragment.setMenuVisibility(false);
        getSupportFragmentManager().beginTransaction()
                .add(R.id.sliding_panel_container, audioPlayerFragment, Integer.toString(SLIDING_PANEL_PLAYER))
                .commit();
        slidingPanelTitle = getString(R.string.audio_player_title);
        slidingPanelFragment = SLIDING_PANEL_PLAYER;

        // Initialise audio playlist fragment
        audioPlaylistFragment = new AudioPlaylistFragment();
        audioPlaylistFragment.setMenuVisibility(false);
        getSupportFragmentManager().beginTransaction().add(R.id.sliding_panel_container, audioPlaylistFragment,
                Integer.toString(SLIDING_PANEL_PLAYLIST)).hide(audioPlaylistFragment).commit();

        // Check connection
        long id = sharedPreferences.getLong("Connection", -1);

        if (id < 0) {
            Intent connectionsIntent = new Intent(this, ConnectionActivity.class);
            startActivityForResult(connectionsIntent, RESULT_CODE_CONNECTIONS);
        } else {
            Connection connection = db.getConnection(id);
            RESTService.getInstance().setConnection(connection);
        }
    } else {
        // Reload fragments
        mediaBrowserFragment = getSupportFragmentManager()
                .findFragmentByTag(Integer.toString(MENU_MEDIA_BROWSER));
        audioPlayerSmallFragment = (AudioPlayerSmallFragment) getSupportFragmentManager()
                .findFragmentByTag(Integer.toString(SLIDING_PANEL_SMALL_PLAYER));
        audioPlayerFragment = (AudioPlayerFragment) getSupportFragmentManager()
                .findFragmentByTag(Integer.toString(SLIDING_PANEL_PLAYER));
        audioPlaylistFragment = (AudioPlaylistFragment) getSupportFragmentManager()
                .findFragmentByTag(Integer.toString(SLIDING_PANEL_PLAYLIST));

        // Restore activity state variables
        slidingPanelFragment = savedInstanceState.getInt(STATE_SLIDING_PANEL_FRAGMENT);
        slidingPanelTitle = savedInstanceState.getString(STATE_SLIDING_PANEL_TITLE);
        title = savedInstanceState.getString(STATE_MAIN_TITLE);

        if (savedInstanceState.getSerializable(STATE_SLIDING_PANEL) == PanelState.EXPANDED) {
            slidingPanel.setPanelState(PanelState.EXPANDED);
            slidingPanelListener.onPanelSlide(slidingPanel, 1.0f);
            slidingPanelListener.onPanelExpanded(slidingPanel);
        } else {
            slidingPanel.setPanelState(PanelState.COLLAPSED);
            slidingPanelListener.onPanelSlide(slidingPanel, 0.0f);
            slidingPanelListener.onPanelCollapsed(slidingPanel);
        }
    }

    // Add fragment back stack listener
    getSupportFragmentManager().addOnBackStackChangedListener(this);
}

From source file:com.android.gallery3d.app.PhotoPage.java

@Override
public void onCreate(Bundle data, Bundle restoreState) {
    super.onCreate(data, restoreState);
    mActionBar = mActivity.getGalleryActionBar();
    mSelectionManager = new SelectionManager(mActivity, false);
    mMenuExecutor = new MenuExecutor(mActivity, mSelectionManager);

    mPhotoView = new PhotoView(mActivity);
    mPhotoView.setListener(this);
    mRootPane.addComponent(mPhotoView);//from  w  w w .java2 s . co  m
    mApplication = (GalleryApp) ((Activity) mActivity).getApplication();
    mOrientationManager = mActivity.getOrientationManager();
    mActivity.getGLRoot().setOrientationSource(mOrientationManager);

    mHandler = new SynchronizedHandler(mActivity.getGLRoot()) {
        @Override
        public void handleMessage(Message message) {
            switch (message.what) {
            case MSG_HIDE_BARS: {
                /// M: [BUG.MODIFY] @{
                /* hideBars(); */
                if (mIsActive) {
                    hideBars();
                } else {
                    Log.i(TAG, "<mHandler.MSG_HIDE_BARS> mIsActive = " + mIsActive + ", not hideBars");
                }
                /// @}
                break;
            }
            case MSG_REFRESH_BOTTOM_CONTROLS: {
                if (mCurrentPhoto == message.obj && mBottomControls != null) {
                    mIsPanorama = message.arg1 == 1;
                    mIsPanorama360 = message.arg2 == 1;
                    mBottomControls.refresh();
                    fresh(mBottomControls.getContainerVisibility());
                }
                break;
            }
            case MSG_ON_FULL_SCREEN_CHANGED: {
                if (mAppBridge != null) {
                    mAppBridge.onFullScreenChanged(message.arg1 == 1);
                }
                break;
            }
            case MSG_UPDATE_ACTION_BAR: {
                updateBars();
                break;
            }
            case MSG_WANT_BARS: {
                wantBars();
                break;
            }
            case MSG_UNFREEZE_GLROOT: {
                mActivity.getGLRoot().unfreeze();
                break;
            }
            case MSG_UPDATE_DEFERRED: {
                long nextUpdate = mDeferUpdateUntil - SystemClock.uptimeMillis();
                if (nextUpdate <= 0) {
                    mDeferredUpdateWaiting = false;
                    updateUIForCurrentPhoto();
                } else {
                    mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DEFERRED, nextUpdate);
                }
                break;
            }
            case MSG_ON_CAMERA_CENTER: {
                mSkipUpdateCurrentPhoto = false;
                boolean stayedOnCamera = false;
                if (!mPhotoView.getFilmMode()) {
                    stayedOnCamera = true;
                } else if (SystemClock.uptimeMillis() < mCameraSwitchCutoff
                        && mMediaSet.getMediaItemCount() > 1) {
                    mPhotoView.switchToImage(1);
                } else {
                    if (mAppBridge != null)
                        mPhotoView.setFilmMode(false);
                    stayedOnCamera = true;
                }

                if (stayedOnCamera) {
                    if (mAppBridge == null && mMediaSet.getTotalMediaItemCount() > 1) {
                        launchCamera();
                        /// M: [FEATURE.ADD] @{
                        mPhotoView.stopUpdateEngineData();
                        /// @}
                        /* We got here by swiping from photo 1 to the
                           placeholder, so make it be the thing that
                           is in focus when the user presses back from
                           the camera app */
                        mPhotoView.switchToImage(1);
                    } else {
                        updateBars();
                        /// M: [BUG.MODIFY] getMediaItem(0) may be null, fix JE @{
                        /*updateCurrentPhoto(mModel.getMediaItem(0));*/
                        MediaItem photo = mModel.getMediaItem(0);
                        if (photo != null) {
                            updateCurrentPhoto(photo);
                        }
                        /// @}
                    }
                }
                break;
            }
            case MSG_ON_PICTURE_CENTER: {
                if (!mPhotoView.getFilmMode() && mCurrentPhoto != null
                        && (mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_ACTION) != 0) {
                    /// M: [BUG.MODIFY] @{
                    /*mPhotoView.setFilmMode(true);*/
                    showEmptyAlbumToast(Toast.LENGTH_SHORT);
                    /// @}
                }
                break;
            }
            case MSG_REFRESH_IMAGE: {
                final MediaItem photo = mCurrentPhoto;
                mCurrentPhoto = null;
                updateCurrentPhoto(photo);
                break;
            }
            case MSG_UPDATE_PHOTO_UI: {
                updateUIForCurrentPhoto();
                break;
            }
            case MSG_UPDATE_SHARE_URI: {
                /// M: [BUG.ADD] @{
                // never update share uri when PhotoPage is not active
                if (!mIsActive) {
                    break;
                }
                /// @}
                /// M: [BUG.MARK] @{
                // No matter what message.obj is, we update share intent for current photo
                /* if (mCurrentPhoto == message.obj) {*/
                /// @}
                boolean isPanorama360 = message.arg1 != 0;
                Uri contentUri = mCurrentPhoto.getContentUri();
                Intent panoramaIntent = null;
                if (isPanorama360) {
                    panoramaIntent = createSharePanoramaIntent(contentUri);
                }
                Intent shareIntent = createShareIntent(mCurrentPhoto);

                mActionBar.setShareIntents(panoramaIntent, shareIntent, PhotoPage.this);
                setNfcBeamPushUri(contentUri);
                /// M: [BUG.MARK] @{
                // }
                /// @}
                break;
            }
            case MSG_UPDATE_PANORAMA_UI: {
                if (mCurrentPhoto == message.obj) {
                    boolean isPanorama360 = message.arg1 != 0;
                    updatePanoramaUI(isPanorama360);
                }
                break;
            }
            default:
                throw new AssertionError(message.what);
            }
        }
    };

    mSetPathString = data.getString(KEY_MEDIA_SET_PATH);
    /// M: [FEATURE.ADD] [Camera independent from Gallery] @{
    mLaunchFromCamera = data.getBoolean(KEY_LAUNCH_FROM_CAMERA, false);
    /// @}
    /// M: [BUG.MODIFY] @{
    // if there is mSetPathString, view is not read only, enable edit
    /*mReadOnlyView = data.getBoolean(KEY_READONLY);*/
    mReadOnlyView = data.getBoolean(KEY_READONLY) && (mSetPathString == null || mSetPathString.equals(""));
    Log.i(TAG, "<onCreate> mSetPathString = " + mSetPathString + ", mReadOnlyView = " + mReadOnlyView);
    /// @}
    mOriginalSetPathString = mSetPathString;
    setupNfcBeamPush();
    String itemPathString = data.getString(KEY_MEDIA_ITEM_PATH);
    Path itemPath = itemPathString != null ? Path.fromString(data.getString(KEY_MEDIA_ITEM_PATH)) : null;
    mTreatBackAsUp = data.getBoolean(KEY_TREAT_BACK_AS_UP, false);
    mStartInFilmstrip = data.getBoolean(KEY_START_IN_FILMSTRIP, false);
    boolean inCameraRoll = data.getBoolean(KEY_IN_CAMERA_ROLL, false);
    mCurrentIndex = data.getInt(KEY_INDEX_HINT, 0);
    if (mSetPathString != null) {
        mShowSpinner = true;
        /// M: [FEATURE.ADD] [Camera independent from Gallery] @{
        // Launch from secure camera
        if (!mSetPathString.equals("/local/all/0") && SecureSource.isSecurePath(mSetPathString)) {
            Log.d(TAG, "<onCreate> secure album");
            mFlags |= FLAG_SHOW_WHEN_LOCKED;
            mSecureAlbum = (SecureAlbum) mActivity.getDataManager().getMediaSet(mSetPathString);
            mSecureAlbum.clearAll();
            ArrayList<String> secureAlbum = (ArrayList<String>) data.getSerializable(SECURE_ALBUM);
            if (secureAlbum != null) {
                int albumCount = secureAlbum.size();
                Log.d(TAG, "<onCreate> albumCount " + albumCount);
                for (int i = 0; i < albumCount; i++) {
                    try {
                        String[] albumItem = secureAlbum.get(i).split("\\+");
                        int albumItemSize = albumItem.length;
                        Log.d(TAG, "<onCreate> albumItemSize " + albumItemSize);
                        if (albumItemSize == 2) {
                            int id = Integer.parseInt(albumItem[0].trim());
                            boolean isVideo = Boolean.parseBoolean(albumItem[1].trim());
                            Log.d(TAG, "<onCreate> secure item : id " + id + ", isVideo " + isVideo);
                            mSecureAlbum.addMediaItem(isVideo, id);
                        }
                    } catch (NullPointerException ex) {
                        Log.e(TAG, "<onCreate> exception " + ex);
                    } catch (PatternSyntaxException ex) {
                        Log.e(TAG, "<onCreate> exception " + ex);
                    } catch (NumberFormatException ex) {
                        Log.e(TAG, "<onCreate> exception " + ex);
                    }
                }
            }
            mShowSpinner = false;
            mSetPathString = "/filter/empty/{" + mSetPathString + "}";
            mSetPathString = "/combo/item/{" + mSetPathString + "}";
        }
        /// @}
        mAppBridge = (AppBridge) data.getParcelable(KEY_APP_BRIDGE);
        if (mAppBridge != null) {
            mShowBars = false;
            mHasCameraScreennailOrPlaceholder = true;
            mAppBridge.setServer(this);

            // Get the ScreenNail from AppBridge and register it.
            int id = SnailSource.newId();
            Path screenNailSetPath = SnailSource.getSetPath(id);
            Path screenNailItemPath = SnailSource.getItemPath(id);
            mScreenNailSet = (SnailAlbum) mActivity.getDataManager().getMediaObject(screenNailSetPath);
            mScreenNailItem = (SnailItem) mActivity.getDataManager().getMediaObject(screenNailItemPath);
            mScreenNailItem.setScreenNail(mAppBridge.attachScreenNail());

            if (data.getBoolean(KEY_SHOW_WHEN_LOCKED, false)) {
                // Set the flag to be on top of the lock screen.
                mFlags |= FLAG_SHOW_WHEN_LOCKED;
            }
            // Don't display "empty album" action item for capture intents.
            if (!mSetPathString.equals("/local/all/0")) {
                // Check if the path is a secure album.
                if (SecureSource.isSecurePath(mSetPathString)) {
                    mSecureAlbum = (SecureAlbum) mActivity.getDataManager().getMediaSet(mSetPathString);
                    mShowSpinner = false;
                }
                mSetPathString = "/filter/empty/{" + mSetPathString + "}";
            }

            // Combine the original MediaSet with the one for ScreenNail
            // from AppBridge.
            mSetPathString = "/combo/item/{" + screenNailSetPath + "," + mSetPathString + "}";

            // Start from the screen nail.
            itemPath = screenNailItemPath;
            /// M: [FEATURE.MARK] [Camera independent from Gallery] @{
            // After camera is removed from gallery, modify the behavior as below:
            // When view the first image in camera folder, slide to left,
            // there is no place holder of camera, and it can not launch camera too.
            /*} else if (inCameraRoll && GalleryUtils.isCameraAvailable(mActivity)) {
                  mSetPathString = "/combo/item/{" + FilterSource.FILTER_CAMERA_SHORTCUT +
              "," + mSetPathString + "}";
                  mCurrentIndex++;
                  mHasCameraScreennailOrPlaceholder = true;*/
            /// @}
            /// M: [FEATURE.ADD] [Camera independent from Gallery] @{
            // When launch from camera, and not from secure camera, we show empty item
            // after delete all images.
        } else if (mLaunchFromCamera && mSecureAlbum == null) {
            mSetPathString = "/filter/empty/{" + mSetPathString + "}";
            Log.i(TAG, "<onCreate> launch from camera, not secure, mSetPathString = " + mSetPathString);
            /// @}
        }

        MediaSet originalSet = mActivity.getDataManager().getMediaSet(mSetPathString);
        if (mHasCameraScreennailOrPlaceholder && originalSet instanceof ComboAlbum) {
            // Use the name of the camera album rather than the default
            // ComboAlbum behavior
            ((ComboAlbum) originalSet).useNameOfChild(1);
        }
        /// M: [BUG.ADD] @{
        // tell PhotoView whether this album is cluster
        if (originalSet != null && originalSet instanceof ClusterAlbum) {
            mPhotoView.setIsCluster(true);
        } else {
            mPhotoView.setIsCluster(false);
        }
        /// @}
        mSelectionManager.setSourceMediaSet(originalSet);
        mSetPathString = "/filter/delete/{" + mSetPathString + "}";
        mMediaSet = (FilterDeleteSet) mActivity.getDataManager().getMediaSet(mSetPathString);
        if (mMediaSet == null) {
            Log.w(TAG, "failed to restore " + mSetPathString);
        }
        if (itemPath == null) {
            int mediaItemCount = mMediaSet.getMediaItemCount();
            if (mediaItemCount > 0) {
                if (mCurrentIndex >= mediaItemCount)
                    mCurrentIndex = 0;
                itemPath = mMediaSet.getMediaItem(mCurrentIndex, 1).get(0).getPath();
            } else {
                // Bail out, PhotoPage can't load on an empty album
                return;
            }
        }
        PhotoDataAdapter pda = new PhotoDataAdapter(mActivity, mPhotoView, mMediaSet, itemPath, mCurrentIndex,
                mAppBridge == null ? -1 : 0, mAppBridge == null ? false : mAppBridge.isPanorama(),
                mAppBridge == null ? false : mAppBridge.isStaticCamera());
        mModel = pda;
        mPhotoView.setModel(mModel);

        pda.setDataListener(new PhotoDataAdapter.DataListener() {

            @Override
            public void onPhotoChanged(int index, Path item) {
                int oldIndex = mCurrentIndex;
                mCurrentIndex = index;
                if (mHasCameraScreennailOrPlaceholder) {
                    if (mCurrentIndex > 0) {
                        mSkipUpdateCurrentPhoto = false;
                    }

                    /// M: [FEATURE.MODIFY] @{
                    /*if (oldIndex == 0 && mCurrentIndex > 0
                     && !mPhotoView.getFilmMode()) {
                     mPhotoView.setFilmMode(true);*/
                    if (oldIndex == 0 && mCurrentIndex > 0) {
                        onActionBarAllowed(true);
                        mPhotoView.setFilmMode(false);
                        /// @}
                        if (mAppBridge != null) {
                            UsageStatistics.onEvent("CameraToFilmstrip", UsageStatistics.TRANSITION_SWIPE,
                                    null);
                        }
                    } else if (oldIndex == 2 && mCurrentIndex == 1) {
                        mCameraSwitchCutoff = SystemClock.uptimeMillis() + CAMERA_SWITCH_CUTOFF_THRESHOLD_MS;
                        mPhotoView.stopScrolling();
                    } else if (oldIndex >= 1 && mCurrentIndex == 0) {
                        mPhotoView.setWantPictureCenterCallbacks(true);
                        mSkipUpdateCurrentPhoto = true;
                    }
                }
                if (!mSkipUpdateCurrentPhoto) {
                    if (item != null) {
                        MediaItem photo = mModel.getMediaItem(0);
                        if (photo != null)
                            updateCurrentPhoto(photo);
                    }
                    updateBars();
                }
                // Reset the timeout for the bars after a swipe
                /// M: [DEBUG.ADD] @{
                Log.i(TAG, "<onPhotoChanged> refreshHidingMessage");
                /// @}
                refreshHidingMessage();
            }

            @Override
            public void onLoadingFinished(boolean loadingFailed) {
                /// M: [BUG.ADD] @{
                mLoadingFinished = true;
                // Refresh bottom controls when data loading done
                refreshBottomControlsWhenReady();
                /// @}
                if (!mModel.isEmpty()) {
                    MediaItem photo = mModel.getMediaItem(0);
                    if (photo != null)
                        updateCurrentPhoto(photo);
                } else if (mIsActive) {
                    // We only want to finish the PhotoPage if there is no
                    // deletion that the user can undo.
                    if (mMediaSet.getNumberOfDeletions() == 0) {
                        /// M: [BUG.ADD] pause PhotoView before finish PhotoPage @{
                        mPhotoView.pause();
                        /// @}
                        mActivity.getStateManager().finishState(PhotoPage.this);
                    }
                }
            }

            @Override
            public void onLoadingStarted() {
                /// M: [BUG.ADD] @{
                mLoadingFinished = false;
                /// @}
            }
        });
    } else {
        // Get default media set by the URI
        MediaItem mediaItem = (MediaItem) mActivity.getDataManager().getMediaObject(itemPath);
        /// M: [BUG.ADD] fix JE when mediaItem is deleted@{
        if (mediaItem == null) {
            Toast.makeText(((Activity) mActivity), R.string.no_such_item, Toast.LENGTH_LONG).show();
            mPhotoView.pause();
            mActivity.getStateManager().finishState(this);
            return;
        }
        /// @}
        /// M: [BUG.ADD] @{
        // no PhotoDataAdapter style loading in SinglePhotoDataAdapter
        mLoadingFinished = true;
        /// @}
        mModel = new SinglePhotoDataAdapter(mActivity, mPhotoView, mediaItem);
        mPhotoView.setModel(mModel);
        updateCurrentPhoto(mediaItem);
        mShowSpinner = false;
    }

    mPhotoView.setFilmMode(mStartInFilmstrip && mMediaSet.getMediaItemCount() > 1);
    RelativeLayout galleryRoot = (RelativeLayout) ((Activity) mActivity)
            .findViewById(mAppBridge != null ? R.id.content : R.id.gallery_root);
    if (galleryRoot != null) {
        if (mSecureAlbum == null) {
            mBottomControls = new PhotoPageBottomControls(this, mActivity, galleryRoot);
        }
    }
    /// M: [BUG.MODIFY] set change listener to current GLRootView @{
    // onResume also need to set this listener, so modify it.
    /*((GLRootView) mActivity.getGLRoot()).setOnSystemUiVisibilityChangeListener(
        new View.OnSystemUiVisibilityChangeListener() {
        @Override
            public void onSystemUiVisibilityChange(int visibility) {
                int diff = mLastSystemUiVis ^ visibility;
                mLastSystemUiVis = visibility;
                if ((diff & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0
                        && (visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                    /// M: [BUG.MODIFY] Don't need show bars in camera preview. @{
                    /*showBars();*/
    /*wantBars();
    /// @}
    }
    }
    });*/
    setOnSystemUiVisibilityChangeListener();
    /// @}
    /// M: [FEATURE.ADD] VTSP: share as video @{
    initAnimatedContentSharer();
    /// @}
    /// M: [FEATURE.ADD] add backward controller for layer @{
    mPhotoView.setBackwardControllerForLayerManager(mBackwardContollerForLayer);
    /// @}
}

From source file:com.irccloud.android.activity.MainActivity.java

@SuppressLint("NewApi")
@SuppressWarnings({ "deprecation", "unchecked" })
@Override/*w w w . ja v a 2s .c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    suggestionsTimer = new Timer("suggestions-timer");
    countdownTimer = new Timer("messsage-countdown-timer");

    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    registerReceiver(screenReceiver, filter);

    if (Build.VERSION.SDK_INT >= 21) {
        Bitmap cloud = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        if (cloud != null) {
            setTaskDescription(new ActivityManager.TaskDescription(getResources().getString(R.string.app_name),
                    cloud, 0xFFF2F7FC));
            cloud.recycle();
        }
    }
    setContentView(R.layout.activity_message);
    try {
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    } catch (Throwable t) {
    }

    suggestionsAdapter = new SuggestionsAdapter();
    progressBar = (ProgressBar) findViewById(R.id.progress);
    errorMsg = (TextView) findViewById(R.id.errorMsg);
    buffersListView = findViewById(R.id.BuffersList);
    messageContainer = (LinearLayout) findViewById(R.id.messageContainer);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);

    redColor = getResources().getColor(R.color.highlight_red);
    blueColor = getResources().getColor(R.color.dark_blue);

    messageTxt = (ActionEditText) findViewById(R.id.messageTxt);
    messageTxt.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (sendBtn.isEnabled()
                    && NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED
                    && event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER
                    && messageTxt.getText() != null && messageTxt.getText().length() > 0) {
                sendBtn.setEnabled(false);
                new SendTask().execute((Void) null);
            } else if (keyCode == KeyEvent.KEYCODE_TAB) {
                if (event.getAction() == KeyEvent.ACTION_DOWN)
                    nextSuggestion();
                return true;
            }
            return false;
        }
    });
    messageTxt.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (drawerLayout != null && v == messageTxt && hasFocus) {
                drawerLayout.closeDrawers();
                update_suggestions(false);
            } else if (!hasFocus) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        suggestionsContainer.setVisibility(View.INVISIBLE);
                    }
                });
            }
        }
    });
    messageTxt.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (drawerLayout != null) {
                drawerLayout.closeDrawers();
            }
        }
    });
    messageTxt.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            if (sendBtn.isEnabled()
                    && NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED
                    && actionId == EditorInfo.IME_ACTION_SEND && messageTxt.getText() != null
                    && messageTxt.getText().length() > 0) {
                sendBtn.setEnabled(false);
                new SendTask().execute((Void) null);
            }
            return true;
        }
    });
    textWatcher = new TextWatcher() {
        public void afterTextChanged(Editable s) {
            Object[] spans = s.getSpans(0, s.length(), Object.class);
            for (Object o : spans) {
                if (((s.getSpanFlags(o) & Spanned.SPAN_COMPOSING) != Spanned.SPAN_COMPOSING)
                        && (o.getClass() == StyleSpan.class || o.getClass() == ForegroundColorSpan.class
                                || o.getClass() == BackgroundColorSpan.class
                                || o.getClass() == UnderlineSpan.class || o.getClass() == URLSpan.class)) {
                    s.removeSpan(o);
                }
            }
            if (s.length() > 0
                    && NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED) {
                sendBtn.setEnabled(true);
                if (Build.VERSION.SDK_INT >= 11)
                    sendBtn.setAlpha(1);
            } else {
                sendBtn.setEnabled(false);
                if (Build.VERSION.SDK_INT >= 11)
                    sendBtn.setAlpha(0.5f);
            }
            String text = s.toString();
            if (text.endsWith("\t")) { //Workaround for Swype
                text = text.substring(0, text.length() - 1);
                messageTxt.setText(text);
                nextSuggestion();
            } else if (suggestionsContainer != null && suggestionsContainer.getVisibility() == View.VISIBLE) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        update_suggestions(false);
                    }
                });
            } else {
                if (suggestionsTimer != null) {
                    if (suggestionsTimerTask != null)
                        suggestionsTimerTask.cancel();
                    suggestionsTimerTask = new TimerTask() {
                        @Override
                        public void run() {
                            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
                            update_suggestions(false);
                        }
                    };
                    suggestionsTimer.schedule(suggestionsTimerTask, 250);
                }
            }
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    };
    messageTxt.addTextChangedListener(textWatcher);
    sendBtn = findViewById(R.id.sendBtn);
    sendBtn.setFocusable(false);
    sendBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED)
                new SendTask().execute((Void) null);
        }
    });

    photoBtn = findViewById(R.id.photoBtn);
    if (photoBtn != null) {
        photoBtn.setFocusable(false);
        photoBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                insertPhoto();
            }
        });
    }
    userListView = findViewById(R.id.usersListFragment);

    View v = getLayoutInflater().inflate(R.layout.actionbar_messageview, null);
    v.findViewById(R.id.actionTitleArea).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            show_topic_popup();
        }
    });

    if (drawerLayout != null) {
        if (findViewById(R.id.usersListFragment2) == null) {
            upDrawable = new DrawerArrowDrawable(this);
            greyColor = upDrawable.getColor();
            ((Toolbar) findViewById(R.id.toolbar)).setNavigationIcon(upDrawable);
            ((Toolbar) findViewById(R.id.toolbar)).setNavigationContentDescription("Show navigation drawer");
            drawerLayout.setDrawerListener(mDrawerListener);
            if (refreshUpIndicatorTask != null)
                refreshUpIndicatorTask.cancel(true);
            refreshUpIndicatorTask = new RefreshUpIndicatorTask();
            refreshUpIndicatorTask.execute((Void) null);
        }
    }
    messageTxt.setDrawerLayout(drawerLayout);

    title = (TextView) v.findViewById(R.id.title);
    subtitle = (TextView) v.findViewById(R.id.subtitle);
    key = (ImageView) v.findViewById(R.id.key);
    getSupportActionBar().setCustomView(v);
    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    if (savedInstanceState != null && savedInstanceState.containsKey("cid")) {
        server = ServersDataSource.getInstance().getServer(savedInstanceState.getInt("cid"));
        buffer = BuffersDataSource.getInstance().getBuffer(savedInstanceState.getInt("bid"));
        backStack = (ArrayList<Integer>) savedInstanceState.getSerializable("backStack");
    }

    if (savedInstanceState != null && savedInstanceState.containsKey("imagecaptureuri"))
        imageCaptureURI = Uri.parse(savedInstanceState.getString("imagecaptureuri"));
    else
        imageCaptureURI = null;

    ConfigInstance config = (ConfigInstance) getLastCustomNonConfigurationInstance();
    if (config != null) {
        imgurTask = config.imgurUploadTask;
        fileUploadTask = config.fileUploadTask;
    }

    drawerLayout.setScrimColor(0);
    drawerLayout.closeDrawers();

    getSupportActionBar().setElevation(0);
}