Example usage for android.os Bundle getLong

List of usage examples for android.os Bundle getLong

Introduction

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

Prototype

public long getLong(String key) 

Source Link

Document

Returns the value associated with the given key, or 0L if no mapping of the desired type exists for the given key.

Usage

From source file:com.android.mms.ui.ComposeMessageActivity.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    if (id == LOAD_TEMPLATE_BY_ID) {
        long rowID = args.getLong("id");
        Uri uri = ContentUris.withAppendedId(Template.CONTENT_URI, rowID);
        return new CursorLoader(this, uri, null, null, null, null);
    } else {//from  w  w w .  ja  v a 2  s .  c om
        return new CursorLoader(this, Template.CONTENT_URI, null, null, null, null);
    }
}

From source file:com.android.contacts.quickcontact.QuickContactActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Trace.beginSection("onCreate()");
    super.onCreate(savedInstanceState);

    if (RequestPermissionsActivity.startPermissionActivity(this)
            || RequestDesiredPermissionsActivity.startPermissionActivity(this)) {
        return;//from w ww  .j  a  v a2  s. co  m
    }

    final int previousScreenType = getIntent().getIntExtra(EXTRA_PREVIOUS_SCREEN_TYPE, ScreenType.UNKNOWN);
    Logger.logScreenView(this, ScreenType.QUICK_CONTACT, previousScreenType);

    if (CompatUtils.isLollipopCompatible()) {
        getWindow().setStatusBarColor(Color.TRANSPARENT);
    }

    processIntent(getIntent());

    // Show QuickContact in front of soft input
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
            WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

    setContentView(R.layout.quickcontact_activity);

    mMaterialColorMapUtils = new MaterialColorMapUtils(getResources());

    mScroller = (MultiShrinkScroller) findViewById(R.id.multiscroller);

    mContactCard = (ExpandingEntryCardView) findViewById(R.id.communication_card);
    mNoContactDetailsCard = (ExpandingEntryCardView) findViewById(R.id.no_contact_data_card);
    mRecentCard = (ExpandingEntryCardView) findViewById(R.id.recent_card);
    mAboutCard = (ExpandingEntryCardView) findViewById(R.id.about_card);

    mCollapsedSuggestionCardView = (CardView) findViewById(R.id.collapsed_suggestion_card);
    mExpandSuggestionCardView = (CardView) findViewById(R.id.expand_suggestion_card);
    mCollapasedSuggestionHeader = findViewById(R.id.collapsed_suggestion_header);
    mCollapsedSuggestionCardTitle = (TextView) findViewById(R.id.collapsed_suggestion_card_title);
    mExpandSuggestionCardTitle = (TextView) findViewById(R.id.expand_suggestion_card_title);
    mSuggestionSummaryPhoto = (ImageView) findViewById(R.id.suggestion_icon);
    mSuggestionForName = (TextView) findViewById(R.id.suggestion_for_name);
    mSuggestionContactsNumber = (TextView) findViewById(R.id.suggestion_for_contacts_number);
    mSuggestionList = (LinearLayout) findViewById(R.id.suggestion_list);
    mSuggestionsCancelButton = (Button) findViewById(R.id.cancel_button);
    mSuggestionsLinkButton = (Button) findViewById(R.id.link_button);
    if (savedInstanceState != null) {
        mIsSuggestionListCollapsed = savedInstanceState.getBoolean(KEY_IS_SUGGESTION_LIST_COLLAPSED, true);
        mPreviousContactId = savedInstanceState.getLong(KEY_PREVIOUS_CONTACT_ID);
        mSuggestionsShouldAutoSelected = savedInstanceState.getBoolean(KEY_SUGGESTIONS_AUTO_SELECTED, true);
        mSelectedAggregationIds = (TreeSet<Long>) savedInstanceState
                .getSerializable(KEY_SELECTED_SUGGESTION_CONTACTS);
    } else {
        mIsSuggestionListCollapsed = true;
        mSelectedAggregationIds.clear();
    }
    if (mSelectedAggregationIds.isEmpty()) {
        disableLinkButton();
    } else {
        enableLinkButton();
    }
    mCollapasedSuggestionHeader.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            mCollapsedSuggestionCardView.setVisibility(View.GONE);
            mExpandSuggestionCardView.setVisibility(View.VISIBLE);
            mIsSuggestionListCollapsed = false;
            mExpandSuggestionCardTitle.requestFocus();
            mExpandSuggestionCardTitle.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
        }
    });

    mSuggestionsCancelButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            mCollapsedSuggestionCardView.setVisibility(View.VISIBLE);
            mExpandSuggestionCardView.setVisibility(View.GONE);
            mIsSuggestionListCollapsed = true;
        }
    });

    mNoContactDetailsCard.setOnClickListener(mEntryClickHandler);
    mContactCard.setOnClickListener(mEntryClickHandler);
    mContactCard.setExpandButtonText(getResources().getString(R.string.expanding_entry_card_view_see_all));
    mContactCard.setOnCreateContextMenuListener(mEntryContextMenuListener);

    mRecentCard.setOnClickListener(mEntryClickHandler);
    mRecentCard.setTitle(getResources().getString(R.string.recent_card_title));

    mAboutCard.setOnClickListener(mEntryClickHandler);
    mAboutCard.setOnCreateContextMenuListener(mEntryContextMenuListener);

    mPhotoView = (QuickContactImageView) findViewById(R.id.photo);
    final View transparentView = findViewById(R.id.transparent_view);
    if (mScroller != null) {
        transparentView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mScroller.scrollOffBottom();
            }
        });
    }

    // Allow a shadow to be shown under the toolbar.
    ViewUtil.addRectangularOutlineProvider(findViewById(R.id.toolbar_parent), getResources());

    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setActionBar(toolbar);
    getActionBar().setTitle(null);
    // Put a TextView with a known resource id into the ActionBar. This allows us to easily
    // find the correct TextView location & size later.
    toolbar.addView(getLayoutInflater().inflate(R.layout.quickcontact_title_placeholder, null));

    mHasAlreadyBeenOpened = savedInstanceState != null;
    mIsEntranceAnimationFinished = mHasAlreadyBeenOpened;
    mWindowScrim = new ColorDrawable(SCRIM_COLOR);
    mWindowScrim.setAlpha(0);
    getWindow().setBackgroundDrawable(mWindowScrim);

    mScroller.initialize(mMultiShrinkScrollerListener, mExtraMode == MODE_FULLY_EXPANDED);
    // mScroller needs to perform asynchronous measurements after initalize(), therefore
    // we can't mark this as GONE.
    mScroller.setVisibility(View.INVISIBLE);

    setHeaderNameText(R.string.missing_name);

    mSelectAccountFragmentListener = (SelectAccountDialogFragmentListener) getFragmentManager()
            .findFragmentByTag(FRAGMENT_TAG_SELECT_ACCOUNT);
    if (mSelectAccountFragmentListener == null) {
        mSelectAccountFragmentListener = new SelectAccountDialogFragmentListener();
        getFragmentManager().beginTransaction()
                .add(0, mSelectAccountFragmentListener, FRAGMENT_TAG_SELECT_ACCOUNT).commit();
        mSelectAccountFragmentListener.setRetainInstance(true);
    }
    mSelectAccountFragmentListener.setQuickContactActivity(this);

    SchedulingUtils.doOnPreDraw(mScroller, /* drawNextFrame = */ true, new Runnable() {
        @Override
        public void run() {
            if (!mHasAlreadyBeenOpened) {
                // The initial scrim opacity must match the scrim opacity that would be
                // achieved by scrolling to the starting position.
                final float alphaRatio = mExtraMode == MODE_FULLY_EXPANDED ? 1
                        : mScroller.getStartingTransparentHeightRatio();
                final int duration = getResources().getInteger(android.R.integer.config_shortAnimTime);
                final int desiredAlpha = (int) (0xFF * alphaRatio);
                ObjectAnimator o = ObjectAnimator.ofInt(mWindowScrim, "alpha", 0, desiredAlpha)
                        .setDuration(duration);

                o.start();
            }
        }
    });

    if (savedInstanceState != null) {
        final int color = savedInstanceState.getInt(KEY_THEME_COLOR, 0);
        SchedulingUtils.doOnPreDraw(mScroller, /* drawNextFrame = */ false, new Runnable() {
            @Override
            public void run() {
                // Need to wait for the pre draw before setting the initial scroll
                // value. Prior to pre draw all scroll values are invalid.
                if (mHasAlreadyBeenOpened) {
                    mScroller.setVisibility(View.VISIBLE);
                    mScroller.setScroll(mScroller.getScrollNeededToBeFullScreen());
                }
                // Need to wait for pre draw for setting the theme color. Setting the
                // header tint before the MultiShrinkScroller has been measured will
                // cause incorrect tinting calculations.
                if (color != 0) {
                    setThemeColor(mMaterialColorMapUtils.calculatePrimaryAndSecondaryColor(color));
                }
            }
        });
    }

    Trace.endSection();
}

From source file:com.xandy.calendar.EventInfoFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (savedInstanceState != null) {
        mIsDialog = savedInstanceState.getBoolean(BUNDLE_KEY_IS_DIALOG, false);
        mWindowStyle = savedInstanceState.getInt(BUNDLE_KEY_WINDOW_STYLE, DIALOG_WINDOW_STYLE);
        mDeleteDialogVisible = savedInstanceState.getBoolean(BUNDLE_KEY_DELETE_DIALOG_VISIBLE, false);
        mCalendarColor = savedInstanceState.getInt(BUNDLE_KEY_CALENDAR_COLOR);
        mCalendarColorInitialized = savedInstanceState.getBoolean(BUNDLE_KEY_CALENDAR_COLOR_INIT);
        mOriginalColor = savedInstanceState.getInt(BUNDLE_KEY_ORIGINAL_COLOR);
        mOriginalColorInitialized = savedInstanceState.getBoolean(BUNDLE_KEY_ORIGINAL_COLOR_INIT);
        mCurrentColor = savedInstanceState.getInt(BUNDLE_KEY_CURRENT_COLOR);
        mCurrentColorInitialized = savedInstanceState.getBoolean(BUNDLE_KEY_CURRENT_COLOR_INIT);
        mCurrentColorKey = savedInstanceState.getInt(BUNDLE_KEY_CURRENT_COLOR_KEY);

        mTentativeUserSetResponse = savedInstanceState.getInt(BUNDLE_KEY_TENTATIVE_USER_RESPONSE,
                Attendees.ATTENDEE_STATUS_NONE);
        if (mTentativeUserSetResponse != Attendees.ATTENDEE_STATUS_NONE && mEditResponseHelper != null) {
            // If the edit response helper dialog is open, we'll need to
            // know if either of the choices were selected.
            mEditResponseHelper.setWhichEvents(savedInstanceState.getInt(BUNDLE_KEY_RESPONSE_WHICH_EVENTS, -1));
        }/*  www. j  av  a2  s .  c om*/
        mUserSetResponse = savedInstanceState.getInt(BUNDLE_KEY_USER_SET_ATTENDEE_RESPONSE,
                Attendees.ATTENDEE_STATUS_NONE);
        if (mUserSetResponse != Attendees.ATTENDEE_STATUS_NONE) {
            // If the response was set by the user before a configuration
            // change, we'll need to know which choice was selected.
            mWhichEvents = savedInstanceState.getInt(BUNDLE_KEY_RESPONSE_WHICH_EVENTS, -1);
        }

        mReminders = Utils.readRemindersFromBundle(savedInstanceState);
    }

    if (mWindowStyle == DIALOG_WINDOW_STYLE) {
        mView = inflater.inflate(R.layout.event_info_dialog, container, false);
    } else {
        mView = inflater.inflate(R.layout.event_info, container, false);
    }
    mScrollView = (ScrollView) mView.findViewById(R.id.event_info_scroll_view);
    mLoadingMsgView = mView.findViewById(R.id.event_info_loading_msg);
    mErrorMsgView = mView.findViewById(R.id.event_info_error_msg);
    mTitle = (TextView) mView.findViewById(R.id.title);
    mWhenDateTime = (TextView) mView.findViewById(R.id.when_datetime);
    mWhere = (TextView) mView.findViewById(R.id.where);
    mDesc = (ExpandableTextView) mView.findViewById(R.id.description);
    mHeadlines = mView.findViewById(R.id.event_info_headline);
    mLongAttendees = (AttendeesView) mView.findViewById(R.id.long_attendee_list);

    mResponseRadioGroup = (RadioGroup) mView.findViewById(R.id.response_value);

    if (mUri == null) {
        // restore event ID from bundle
        mEventId = savedInstanceState.getLong(BUNDLE_KEY_EVENT_ID);
        mUri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
        mStartMillis = savedInstanceState.getLong(BUNDLE_KEY_START_MILLIS);
        mEndMillis = savedInstanceState.getLong(BUNDLE_KEY_END_MILLIS);
    }

    mAnimateAlpha = ObjectAnimator.ofFloat(mScrollView, "Alpha", 0, 1);
    mAnimateAlpha.setDuration(FADE_IN_TIME);
    mAnimateAlpha.addListener(new AnimatorListenerAdapter() {
        int defLayerType;

        @Override
        public void onAnimationStart(Animator animation) {
            // Use hardware layer for better performance during animation
            defLayerType = mScrollView.getLayerType();
            mScrollView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            // Ensure that the loading message is gone before showing the
            // event info
            mLoadingMsgView.removeCallbacks(mLoadingMsgAlphaUpdater);
            mLoadingMsgView.setVisibility(View.GONE);
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            mScrollView.setLayerType(defLayerType, null);
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            mScrollView.setLayerType(defLayerType, null);
            // Do not cross fade after the first time
            mNoCrossFade = true;
        }
    });

    mLoadingMsgView.setAlpha(0);
    mScrollView.setAlpha(0);
    mErrorMsgView.setVisibility(View.INVISIBLE);
    mLoadingMsgView.postDelayed(mLoadingMsgAlphaUpdater, LOADING_MSG_DELAY);

    // start loading the data

    mHandler.startQuery(TOKEN_QUERY_EVENT, null, mUri, EVENT_PROJECTION, null, null, null);

    View b = mView.findViewById(R.id.delete);
    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mCanModifyCalendar) {
                return;
            }
            mDeleteHelper = new DeleteEventHelper(mContext, mActivity,
                    !mIsDialog && !mIsTabletConfig /* exitWhenDone */);
            mDeleteHelper.setDeleteNotificationListener(EventInfoFragment.this);
            mDeleteHelper.setOnDismissListener(createDeleteOnDismissListener());
            mDeleteDialogVisible = true;
            mDeleteHelper.delete(mStartMillis, mEndMillis, mEventId, -1, onDeleteRunnable);
        }
    });

    b = mView.findViewById(R.id.change_color);
    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mCanModifyCalendar) {
                return;
            }
            showEventColorPickerDialog();
        }
    });

    // Hide Edit/Delete buttons if in full screen mode on a phone
    if (!mIsDialog && !mIsTabletConfig || mWindowStyle == EventInfoFragment.FULL_WINDOW_STYLE) {
        mView.findViewById(R.id.event_info_buttons_container).setVisibility(View.GONE);
    }

    // Create a listener for the email guests button
    emailAttendeesButton = (Button) mView.findViewById(R.id.email_attendees_button);
    if (emailAttendeesButton != null) {
        emailAttendeesButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emailAttendees();
            }
        });
    }

    // Create a listener for the add reminder button
    View reminderAddButton = mView.findViewById(R.id.reminder_add);
    View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addReminder();
            mUserModifiedReminders = true;
        }
    };
    reminderAddButton.setOnClickListener(addReminderOnClickListener);

    // Set reminders variables

    SharedPreferences prefs = GeneralPreferences.getSharedPreferences(mActivity);
    String defaultReminderString = prefs.getString(GeneralPreferences.KEY_DEFAULT_REMINDER,
            GeneralPreferences.NO_REMINDER_STRING);
    mDefaultReminderMinutes = Integer.parseInt(defaultReminderString);
    prepareReminders();

    return mView;
}

From source file:com.android.calendar.EventInfoFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (savedInstanceState != null) {
        mIsDialog = savedInstanceState.getBoolean(BUNDLE_KEY_IS_DIALOG, false);
        mWindowStyle = savedInstanceState.getInt(BUNDLE_KEY_WINDOW_STYLE, DIALOG_WINDOW_STYLE);
        mDeleteDialogVisible = savedInstanceState.getBoolean(BUNDLE_KEY_DELETE_DIALOG_VISIBLE, false);
        mDeleteDialogChoice = savedInstanceState.getInt(BUNDLE_KEY_DELETE_DIALOG_CHOICE, -1);
        mCalendarColor = savedInstanceState.getInt(BUNDLE_KEY_CALENDAR_COLOR);
        mCalendarColorInitialized = savedInstanceState.getBoolean(BUNDLE_KEY_CALENDAR_COLOR_INIT);
        mOriginalColor = savedInstanceState.getInt(BUNDLE_KEY_ORIGINAL_COLOR);
        mOriginalColorInitialized = savedInstanceState.getBoolean(BUNDLE_KEY_ORIGINAL_COLOR_INIT);
        mCurrentColor = savedInstanceState.getInt(BUNDLE_KEY_CURRENT_COLOR);
        mCurrentColorInitialized = savedInstanceState.getBoolean(BUNDLE_KEY_CURRENT_COLOR_INIT);
        mCurrentColorKey = savedInstanceState.getInt(BUNDLE_KEY_CURRENT_COLOR_KEY);

        mTentativeUserSetResponse = savedInstanceState.getInt(BUNDLE_KEY_TENTATIVE_USER_RESPONSE,
                Attendees.ATTENDEE_STATUS_NONE);
        if (mTentativeUserSetResponse != Attendees.ATTENDEE_STATUS_NONE && mEditResponseHelper != null) {
            // If the edit response helper dialog is open, we'll need to
            // know if either of the choices were selected.
            mEditResponseHelper.setWhichEvents(savedInstanceState.getInt(BUNDLE_KEY_RESPONSE_WHICH_EVENTS, -1));
        }/* w w  w  .  j  a  v  a2s.  co  m*/
        mUserSetResponse = savedInstanceState.getInt(BUNDLE_KEY_USER_SET_ATTENDEE_RESPONSE,
                Attendees.ATTENDEE_STATUS_NONE);
        if (mUserSetResponse != Attendees.ATTENDEE_STATUS_NONE) {
            // If the response was set by the user before a configuration
            // change, we'll need to know which choice was selected.
            mWhichEvents = savedInstanceState.getInt(BUNDLE_KEY_RESPONSE_WHICH_EVENTS, -1);
        }

        mReminders = Utils.readRemindersFromBundle(savedInstanceState);
    }

    if (mWindowStyle == DIALOG_WINDOW_STYLE) {
        mView = inflater.inflate(R.layout.event_info_dialog, container, false);
    } else {
        mView = inflater.inflate(R.layout.event_info, container, false);
    }
    mScrollView = (ScrollView) mView.findViewById(R.id.event_info_scroll_view);
    mLoadingMsgView = mView.findViewById(R.id.event_info_loading_msg);
    mErrorMsgView = mView.findViewById(R.id.event_info_error_msg);
    mTitle = (TextView) mView.findViewById(R.id.title);
    mWhenDateTime = (TextView) mView.findViewById(R.id.when_datetime);
    mWhere = (TextView) mView.findViewById(R.id.where);
    mDesc = (ExpandableTextView) mView.findViewById(R.id.description);
    mHeadlines = mView.findViewById(R.id.event_info_headline);
    mLongAttendees = (AttendeesView) mView.findViewById(R.id.long_attendee_list);

    mResponseRadioGroup = (RadioGroup) mView.findViewById(R.id.response_value);

    if (mUri == null) {
        // restore event ID from bundle
        mEventId = savedInstanceState.getLong(BUNDLE_KEY_EVENT_ID);
        mUri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventId);
        mStartMillis = savedInstanceState.getLong(BUNDLE_KEY_START_MILLIS);
        mEndMillis = savedInstanceState.getLong(BUNDLE_KEY_END_MILLIS);
    }

    mAnimateAlpha = ObjectAnimator.ofFloat(mScrollView, "Alpha", 0, 1);
    mAnimateAlpha.setDuration(FADE_IN_TIME);
    mAnimateAlpha.addListener(new AnimatorListenerAdapter() {
        int defLayerType;

        @Override
        public void onAnimationStart(Animator animation) {
            // Use hardware layer for better performance during animation
            defLayerType = mScrollView.getLayerType();
            mScrollView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            // Ensure that the loading message is gone before showing the
            // event info
            mLoadingMsgView.removeCallbacks(mLoadingMsgAlphaUpdater);
            mLoadingMsgView.setVisibility(View.GONE);
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            mScrollView.setLayerType(defLayerType, null);
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            mScrollView.setLayerType(defLayerType, null);
            // Do not cross fade after the first time
            mNoCrossFade = true;
        }
    });

    mLoadingMsgView.setAlpha(0);
    mScrollView.setAlpha(0);
    mErrorMsgView.setVisibility(View.INVISIBLE);
    mLoadingMsgView.postDelayed(mLoadingMsgAlphaUpdater, LOADING_MSG_DELAY);

    // start loading the data

    mHandler.startQuery(TOKEN_QUERY_EVENT, null, mUri, EVENT_PROJECTION, null, null, null);

    View b = mView.findViewById(R.id.delete);
    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mCanModifyCalendar) {
                return;
            }
            mDeleteHelper = new DeleteEventHelper(mContext, mActivity,
                    !mIsDialog && !mIsTabletConfig /* exitWhenDone */);
            mDeleteHelper.setDeleteNotificationListener(EventInfoFragment.this);
            mDeleteHelper.setOnDismissListener(createDeleteOnDismissListener());
            mDeleteDialogVisible = true;
            mDeleteHelper.delete(mStartMillis, mEndMillis, mEventId, -1, onDeleteRunnable);
        }
    });

    b = mView.findViewById(R.id.change_color);
    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mCanModifyCalendar) {
                return;
            }
            showEventColorPickerDialog();
        }
    });

    // Hide Edit/Delete buttons if in full screen mode on a phone
    if (!mIsDialog && !mIsTabletConfig || mWindowStyle == EventInfoFragment.FULL_WINDOW_STYLE) {
        mView.findViewById(R.id.event_info_buttons_container).setVisibility(View.GONE);
    }

    // Create a listener for the email guests button
    emailAttendeesButton = (Button) mView.findViewById(R.id.email_attendees_button);
    if (emailAttendeesButton != null) {
        emailAttendeesButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emailAttendees();
            }
        });
    }

    // Create a listener for the add reminder button
    View reminderAddButton = mView.findViewById(R.id.reminder_add);
    View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addReminder();
            mUserModifiedReminders = true;
        }
    };
    reminderAddButton.setOnClickListener(addReminderOnClickListener);

    // Set reminders variables

    SharedPreferences prefs = GeneralPreferences.getSharedPreferences(mActivity);
    String defaultReminderString = prefs.getString(GeneralPreferences.KEY_DEFAULT_REMINDER,
            GeneralPreferences.NO_REMINDER_STRING);
    mDefaultReminderMinutes = Integer.parseInt(defaultReminderString);
    prepareReminders();

    return mView;
}

From source file:com.google.android.apps.forscience.whistlepunk.review.RunReviewFragment.java

private void attachToRun(final Experiment experiment, final ExperimentRun run,
        final Bundle savedInstanceState) {
    mExperimentRun = run;/*from w  w w  .  j a va 2  s .  c  om*/
    mExperiment = experiment;
    final View rootView = getView();
    if (rootView == null) {
        if (getActivity() != null) {
            ((AppCompatActivity) getActivity()).supportStartPostponedEnterTransition();
        }
        return;
    }
    final RecyclerView pinnedNoteList = (RecyclerView) rootView.findViewById(R.id.pinned_note_list);
    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    pinnedNoteList.setLayoutManager(layoutManager);

    sortPinnedNotes(run.getPinnedNotes());
    mPinnedNoteAdapter = new PinnedNoteAdapter(run.getPinnedNotes(), run.getFirstTimestamp());
    mPinnedNoteAdapter.setListItemModifyListener(new PinnedNoteAdapter.ListItemEditListener() {
        @Override
        public void onListItemEdit(final Label item) {
            launchLabelEdit(item, run, item.getValue(), item.getTimeStamp());
        }

        @Override
        public void onListItemDelete(final Label item) {
            final DataController dc = getDataController();
            Snackbar bar = AccessibilityUtils.makeSnackbar(getView(),
                    getActivity().getResources().getString(R.string.snackbar_note_deleted),
                    Snackbar.LENGTH_SHORT);

            // On undo, re-add the item to the database and the pinned note list.
            bar.setAction(R.string.snackbar_undo, new View.OnClickListener() {
                boolean mUndone = false;

                @Override
                public void onClick(View v) {
                    if (mUndone) {
                        return;
                    }
                    mUndone = true;
                    Label label;
                    if (item instanceof TextLabel) {
                        String title = ((TextLabel) item).getText();
                        label = new TextLabel(title, dc.generateNewLabelId(), item.getRunId(),
                                item.getTimeStamp());
                    } else if (item instanceof PictureLabel) {
                        label = new PictureLabel(((PictureLabel) item).getFilePath(),
                                ((PictureLabel) item).getCaption(), dc.generateNewLabelId(), item.getRunId(),
                                item.getTimeStamp());
                    } else if (item instanceof SensorTriggerLabel) {
                        label = new SensorTriggerLabel(dc.generateNewLabelId(), item.getRunId(),
                                item.getTimeStamp(), item.getValue());
                    } else {
                        // Not a known label type
                        return;
                    }
                    label.setExperimentId(item.getExperimentId());
                    dc.addLabel(label, new LoggingConsumer<Label>(TAG, "re-add deleted label") {
                        @Override
                        public void success(Label label) {
                            mPinnedNoteAdapter.insertNote(label);
                            mChartController.setLabels(mPinnedNoteAdapter.getPinnedNotes());
                            WhistlePunkApplication.getUsageTracker(getActivity()).trackEvent(
                                    TrackerConstants.CATEGORY_NOTES, TrackerConstants.ACTION_DELETE_UNDO,
                                    TrackerConstants.LABEL_RUN_REVIEW,
                                    TrackerConstants.getLabelValueType(item));
                        }
                    });
                }
            });

            // Delete the item immediately, and remove it from the pinned note list.
            dc.deleteLabel(item, new LoggingConsumer<Success>(TAG, "delete label") {
                @Override
                public void success(Success value) {
                    mPinnedNoteAdapter.deleteNote(item);
                    mChartController.setLabels(mPinnedNoteAdapter.getPinnedNotes());
                    WhistlePunkApplication.getUsageTracker(getActivity()).trackEvent(
                            TrackerConstants.CATEGORY_NOTES, TrackerConstants.ACTION_DELETED,
                            TrackerConstants.LABEL_RUN_REVIEW, TrackerConstants.getLabelValueType(item));
                }
            });
            bar.show();
        }
    });
    mPinnedNoteAdapter.setListItemClickListener(new PinnedNoteAdapter.ListItemClickListener() {
        @Override
        public void onListItemClicked(Label item) {
            // TODO: Animate to the active timestamp.
            mRunReviewOverlay.setActiveTimestamp(item.getTimeStamp());
        }

        @Override
        public void onPictureItemClicked(PictureLabel item) {
            launchPicturePreview(item);
        }
    });
    pinnedNoteList.setAdapter(mPinnedNoteAdapter);

    // Re-enable appropriate menu options.
    getActivity().invalidateOptionsMenu();

    hookUpExperimentDetailsArea(run, rootView);

    // Load the data for the first sensor only.
    if (savedInstanceState != null) {
        mExternalAxis.zoomTo(savedInstanceState.getLong(KEY_EXTERNAL_AXIS_MINIMUM),
                savedInstanceState.getLong(KEY_EXTERNAL_AXIS_MAXIMUM));
        long overlayTimestamp = savedInstanceState.getLong(KEY_RUN_REVIEW_OVERLAY_TIMESTAMP);
        if (overlayTimestamp != RunReviewOverlay.NO_TIMESTAMP_SELECTED) {
            mRunReviewOverlay.setActiveTimestamp(overlayTimestamp);
        }
    }
    loadRunData(rootView);
    if (getActivity() != null) {
        ((AppCompatActivity) getActivity()).supportStartPostponedEnterTransition();
    }
}

From source file:com.guardtrax.ui.screens.HomeScreen.java

public void onCreate(Bundle savedInstanceState) {
    ctx = this.getApplicationContext();

    super.onCreate(savedInstanceState);

    //restore saved instances if necessary
    if (savedInstanceState != null) {
        Toast.makeText(HomeScreen.this, savedInstanceState.getString("message"), Toast.LENGTH_LONG).show();

        GTConstants.darfileName = savedInstanceState.getString("darfileName");
        GTConstants.tarfileName = savedInstanceState.getString("tarfileName");
        GTConstants.trpfilename = savedInstanceState.getString("trpfilename");
        GTConstants.srpfileName = savedInstanceState.getString("srpfileName");
        Utility.setcurrentState(savedInstanceState.getString("currentState"));
        Utility.setsessionStart(savedInstanceState.getString("getsessionStart"));
        selectedCode = savedInstanceState.getString("selectedCode");
        lunchTime = savedInstanceState.getString("lunchTime");
        breakTime = savedInstanceState.getString("breakTime");
        signaturefileName = savedInstanceState.getString("signaturefileName");
        GTConstants.tourName = savedInstanceState.getString("tourName");
        tourTime = savedInstanceState.getString("tourTime");
        tourEnd = savedInstanceState.getLong("tourEnd");
        lunchoutLocation = savedInstanceState.getInt("lunchoutLocation");
        breakoutLocation = savedInstanceState.getInt("breakoutLocation");
        touritemNumber = savedInstanceState.getInt("touritemNumber");
        chekUpdate = savedInstanceState.getBoolean("chekUpdate");
        GTConstants.sendData = savedInstanceState.getBoolean("send_data");
        GTConstants.isTour = savedInstanceState.getBoolean("isTour");
        GTConstants.isGeoFence = savedInstanceState.getBoolean("isGeoFence");
    } else {// w  ww. j  a  va2s. c  o m
        //set the current state
        Utility.setcurrentState(GTConstants.offShift);

        //set the default startup code to start shift
        selectedCode = "start_shift";
    }

    /*
    //Determine screen size
     if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {     
         Toast.makeText(this, "Large screen",Toast.LENGTH_LONG).show();
     }
     else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {     
         Toast.makeText(this, "Normal sized screen" , Toast.LENGTH_LONG).show();
     } 
     else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {     
         Toast.makeText(this, "Small sized screen" , Toast.LENGTH_LONG).show();
     }
     else {
         Toast.makeText(this, "Screen size is neither large, normal or small" , Toast.LENGTH_LONG).show();
     }
             
      //initialize receiver to monitor for screen on / off
    /*
      IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
      filter.addAction(Intent.ACTION_SCREEN_OFF);
      BroadcastReceiver mReceiver = new ScreenReceiver();
      registerReceiver(mReceiver, filter);
      */

    setContentView(R.layout.homescreen);

    //Create object to call the Database class
    myDatabase = new GuardTraxDB(this);
    preferenceDB = new PreferenceDB(this);
    ftpdatabase = new ftpDataBase(this);
    gtDB = new GTParams(this);
    aDB = new accountsDB(this);
    trafficDB = new trafficDataBase(this);
    tourDB = new tourDataBase(this);

    //check for updates
    if (chekUpdate) {
        //reset the preference value
        chekUpdate = false;

        //check for application updates
        checkUpdate();
    }

    //initialize the message timer
    //initializeOnModeTimerEvent();

    //get the version number and set it in constants
    String version_num = "";

    PackageManager manager = this.getPackageManager();
    try {
        PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
        version_num = info.versionName.toString();

    } catch (NameNotFoundException e) {
        version_num = "0.00.00";
    }
    GTConstants.version = version_num;

    //final TextView version = (TextView) findViewById(R.id.textVersion);
    //version.setText(version_num);

    //set up the animation
    animation.setDuration(500); // duration - half a second
    animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
    animation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely
    animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in

    buttonClick.setDuration(50); // duration - half a second
    buttonClick.setInterpolator(new LinearInterpolator()); // do not alter animation rate
    buttonClick.setRepeatCount(1); // Repeat animation once
    buttonClick.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in

    textWarning = (TextView) findViewById(R.id.txtWarning);
    textWarning.setWidth(500);
    textWarning.setGravity(Gravity.CENTER);

    //allow the text to be clicked if necessary 
    textWarning.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (GTConstants.isTour && GTConstants.tourName.length() > 1)
                displaytourInfo();
        }
    });

    //goto scan page button
    btn_scan_screen = (Button) findViewById(R.id.btn_goto_scan);

    btn_scan_screen.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_scan_screen.startAnimation(buttonClick);

            //Utility.showScan(HomeScreen.this);
            scan_click(false);
        }
    });

    //goto report page button
    btn_report_screen = (Button) findViewById(R.id.btn_goto_report);
    btn_report_screen.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_report_screen.startAnimation(buttonClick);

            report_click();
        }
    });

    //goto dial page button
    btn_dial_screen = (Button) findViewById(R.id.btn_goto_dial);
    btn_dial_screen.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_dial_screen.startAnimation(buttonClick);

            dial_click();
        }
    });

    //microphone button
    btn_mic = (Button) findViewById(R.id.btn_mic);
    btn_mic.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_mic.startAnimation(buttonClick);

            voice_click();
        }

    });

    //camera button
    btn_camera = (Button) findViewById(R.id.btn_camera);
    btn_camera.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_camera.startAnimation(buttonClick);

            camera_click();
        }
    });

    //video button
    btn_video = (Button) findViewById(R.id.btn_video);
    btn_video.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_video.startAnimation(buttonClick);

            video_click();
        }

    });

    // Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable.
    btn_send = (Button) findViewById(R.id.btn_Send);
    btn_send.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            //prevent multiple fast clicking
            if (SystemClock.elapsedRealtime() - mLastClickTime < 2000)
                return;

            mLastClickTime = SystemClock.elapsedRealtime();

            incidentcodeSent = true;

            btn_send.startAnimation(buttonClick);

            //if start shift has not been sent then the device is in do not send data mode.  Warn the user 
            if (Utility.getcurrentState().equals(GTConstants.offShift) && !selectedCode.equals("start_shift")) {
                show_alert_title = "Error";
                show_alert_message = "You must start your shift!";
                showAlert(show_alert_title, show_alert_message, true);

                //set spinner back to start shift
                spinner.setSelection(0);
            } else {
                if (Utility.deviceRegistered()) {
                    show_alert_title = "Success";
                    show_alert_message = "Action success";
                } else {
                    show_alert_title = "Warning";
                    show_alert_message = "You are NOT registered!";

                    showAlert(show_alert_title, show_alert_message, true);
                }

                if (selectedCode.equals("start_shift")) {
                    //if shift already started
                    if (Utility.getcurrentState().equals(GTConstants.onShift)) {
                        show_alert_title = "Warning";
                        show_alert_message = "You must end shift!";

                        showAlert(show_alert_title, show_alert_message, true);

                        //set spinner back to all clear
                        spinner.setSelection(2);
                    } else {
                        ToastMessage.displayToastFromResource(HomeScreen.this, 5, Gravity.CENTER,
                                (ViewGroup) findViewById(R.id.toast_layout_root));

                        pdialog = ProgressDialog.show(HomeScreen.this, "Please wait", "Starting shift ...",
                                true);

                        //set the current state
                        Utility.setcurrentState(GTConstants.onShift);
                        setuserBanner();

                        //wait for start shift actions to complete (or timeout occurs) before dismissing wait dialog
                        new CountDownTimer(5000, 1000) {
                            @Override
                            public void onTick(long millisUntilFinished) {
                                if (start_shift_wait)
                                    pdialog.dismiss();
                            }

                            @Override
                            public void onFinish() {
                                if (!(pdialog == null))
                                    pdialog.dismiss();
                            }
                        }.start();

                        //create dar file
                        try {
                            //create the dar file name
                            GTConstants.darfileName = GTConstants.LICENSE_ID.substring(7) + "_"
                                    + Utility.getUTCDate() + "_" + Utility.getUTCTime() + ".dar";

                            //write the version to the dar file
                            Utility.write_to_file(HomeScreen.this,
                                    GTConstants.dardestinationFolder + GTConstants.darfileName,
                                    "Version;" + GTConstants.version + "\r\n", false);

                            //write the start shift event to the dar file
                            Utility.write_to_file(HomeScreen.this,
                                    GTConstants.dardestinationFolder + GTConstants.darfileName,
                                    "Start shift;" + GTConstants.currentBatteryPercent + ";"
                                            + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n",
                                    true);

                            //create the tar file name if module installed
                            if (GTConstants.isTimeandAttendance) {
                                GTConstants.tarfileName = GTConstants.LICENSE_ID.substring(7) + "_"
                                        + Utility.getUTCDate() + "_" + Utility.getUTCTime() + ".tar";

                                //write the start shift event to the tar file
                                Utility.write_to_file(HomeScreen.this,
                                        GTConstants.dardestinationFolder + GTConstants.tarfileName,
                                        "Name;" + GTConstants.report_name + "\r\n" + "Start shift;"
                                                + Utility.getLocalTime() + ";" + Utility.getLocalDate()
                                                + "\r\n",
                                        false);
                            }

                        } catch (Exception e) {
                            Toast.makeText(HomeScreen.this, "error = " + e, Toast.LENGTH_LONG).show();
                        }

                        GTConstants.sendData = true;

                        //if not time and attendance then send start shift event now, otherwise wait till after location scan
                        send_event("11");

                        //set the session start time
                        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yy HH:mm:ss");
                        Utility.setsessionStart(sdf.format(new Date()));

                        //reset the server connection flag
                        Utility.resetisConnecting();

                        //start the GPS location service
                        MainService.openLocationListener();

                        //set spinner back to all clear
                        spinner.setSelection(2);

                        setwarningText("");

                        if (GTConstants.isTimeandAttendance) {
                            show_taa_scan(true, false);
                        }
                    }

                } else if (selectedCode.equals("end_shift")) {
                    if (!Utility.getcurrentState().equals(GTConstants.onShift)
                            && GTConstants.isTimeandAttendance) {
                        show_alert_title = "Error";
                        show_alert_message = "You must end your Lunch / Break!";
                        showAlert(show_alert_title, show_alert_message, true);

                        //set spinner back to start shift
                        spinner.setSelection(2);
                    } else {
                        btn_send.setEnabled(false);
                        if (GTConstants.isTimeandAttendance) {
                            show_taa_scan(false, true);
                        } else
                            endshiftCode();
                    }
                } else {
                    if (Utility.isselectionValid(HomeScreen.this, selectedCode)) {
                        //if time and attendance then write to file
                        if (selectedCode.equalsIgnoreCase(GTConstants.lunchin)
                                || selectedCode.equalsIgnoreCase(GTConstants.lunchout)
                                || selectedCode.equalsIgnoreCase(GTConstants.startbreak)
                                || selectedCode.equalsIgnoreCase(GTConstants.endbreak)) {
                            if (GTConstants.isTimeandAttendance)
                                Utility.write_to_file(HomeScreen.this,
                                        GTConstants.dardestinationFolder + GTConstants.tarfileName,
                                        spinner.getSelectedItem().toString() + ";" + Utility.getLocalTime()
                                                + ";" + Utility.getLocalDate() + "\r\n",
                                        true);

                            if (selectedCode.equalsIgnoreCase(GTConstants.lunchin)) {
                                Utility.setcurrentState(GTConstants.onLunch);
                                Utility.setlunchStart(true);
                                setuserBanner();
                            }

                            if (selectedCode.equalsIgnoreCase(GTConstants.startbreak)) {
                                Utility.setcurrentState(GTConstants.onBreak);
                                Utility.setbreakStart(true);
                                setuserBanner();
                            }

                            if (selectedCode.equalsIgnoreCase(GTConstants.lunchout)) {
                                Utility.setcurrentState(GTConstants.onShift);
                                lunchTime = Utility.gettimeDiff(Utility.getlunchStart(),
                                        Utility.getLocalDateTime());
                                setuserBanner();
                            }

                            if (selectedCode.equalsIgnoreCase(GTConstants.endbreak)) {
                                Utility.setcurrentState(GTConstants.onShift);
                                breakTime = Utility.gettimeDiff(Utility.getbreakStart(),
                                        Utility.getLocalDateTime());
                                setuserBanner();
                            }
                        }

                        ToastMessage.displayToastFromResource(HomeScreen.this, 5, Gravity.CENTER,
                                (ViewGroup) findViewById(R.id.toast_layout_root));

                        //save the event description as may be needed for incident report
                        incidentDescription = spinner.getSelectedItem().toString();

                        //write to dar
                        Utility.write_to_file(HomeScreen.this,
                                GTConstants.dardestinationFolder + GTConstants.darfileName,
                                "Event; " + incidentDescription + ";" + Utility.getLocalTime() + ";"
                                        + Utility.getLocalDate() + "\r\n",
                                true);

                        //write to srp
                        if (GTConstants.srpfileName.length() > 1)
                            Utility.write_to_file(HomeScreen.this,
                                    GTConstants.dardestinationFolder + GTConstants.srpfileName,
                                    "Event; " + incidentDescription + ";" + Utility.getLocalTime() + ";"
                                            + Utility.getLocalDate() + "\r\n",
                                    true);

                        //send the data
                        send_event(selectedCode);

                        //ask if user wants to create an incident report.  If the last character is a space, that indicates not to ask for report
                        if (!(incidentDescription.charAt(incidentDescription.length() - 1) == ' ')
                                && !trafficIncident)
                            showYesNoAlert("Report", "Create an Incident Report?", incidentreportScreen);
                        if (!(incidentDescription.charAt(incidentDescription.length() - 1) == ' ')
                                && trafficIncident)
                            showYesNoAlert("Report", "Create a Traffic Violation?", incidentreportScreen);

                        //if last two characters are spaces then ask to write a note
                        if (incidentDescription.charAt(incidentDescription.length() - 1) == ' '
                                && incidentDescription.charAt(incidentDescription.length() - 2) == ' ')
                            showYesNoAlert("Report", "Create a Note?", createNote);

                    }

                    //set spinner back to required state
                    if (selectedCode.equalsIgnoreCase(GTConstants.lunchin))
                        spinner.setSelection(lunchoutLocation);
                    else if (selectedCode.equalsIgnoreCase(GTConstants.startbreak))
                        spinner.setSelection(breakoutLocation);
                    else
                        spinner.setSelection(2);

                }
            }
        }

    });

    //Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).
    spinner = (Spinner) findViewById(R.id.spinner_list);

    //method initialize the spinner action
    initializeSpinnerControl();

    if (GTConstants.service_intent == null) {
        //Condition to check whether the Database exist and if so load data into constants
        try {
            if (preferenceDB.checkDataBase()) {
                preferenceDB.open();

                Cursor cursor = preferenceDB.getRecordByRowID("1");

                preferenceDB.close();

                if (cursor == null)
                    loadPreferenceDataBase();
                else {
                    saveInConstants(cursor);
                    cursor.close();
                }
                syncDB();
                syncFTP();
                syncftpUpload();
            } else {
                preferenceDB.open();
                preferenceDB.close();
                //Toast.makeText(HomeScreen.this, "Path = " + preferenceDB.get_path(), Toast.LENGTH_LONG).show();
                //Toast.makeText(HomeScreen.this, "No database found", Toast.LENGTH_LONG).show();

                loadPreferenceDataBase();

                syncDB();
                syncFTP();
                syncftpUpload();
            }
        } catch (Exception e) {
            preferenceDB.createDataBase();
            loadPreferenceDataBase();
            Toast.makeText(HomeScreen.this, "Creating database", Toast.LENGTH_LONG).show();
        }

        //setup the auxiliary databases
        if (!aDB.checkDataBase()) {
            aDB.open();
            aDB.close();
        }

        if (!ftpdatabase.checkDataBase()) {
            ftpdatabase.open();
            ftpdatabase.close();
        }

        if (!gtDB.checkDataBase()) {
            gtDB.open();
            gtDB.close();
        }

        if (!trafficDB.checkDataBase()) {
            trafficDB.open();
            trafficDB.close();
        }

        if (!tourDB.checkDataBase()) {
            tourDB.open();
            tourDB.close();
        }

        //get the parameters from the parameter database
        loadGTParams();

        //this code starts the main service running which contains all the event timers
        if (Utility.deviceRegistered()) {
            //this is the application started event - sent once when application starts up
            if (savedInstanceState == null)
                send_event("PU");

            initService();
        }
    }

    //if device not registered than go straight to scan screen
    if (!Utility.deviceRegistered()) {
        newRegistration = true;
        //send_data = true;
        scan_click(false);
    }

    //setup the user banner
    setuserBanner();

    //set the warning text
    setwarningText("");

}

From source file:com.cognizant.trumobi.PersonaLauncher.java

/**
 * Restores the previous state, if it exists.
 * /*ww  w.  ja v  a2 s .  c o m*/
 * @param savedState
 *            The previous state.
 */
private void restoreState(Bundle savedState) {
    if (savedState == null) {
        return;
    }

    final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
    if (currentScreen > -1) {
        mWorkspace.setCurrentScreen(currentScreen);
    }

    final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
    if (addScreen > -1) {
        mAddItemCellInfo = new PersonaCellLayout.CellInfo();
        final PersonaCellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
        addItemCellInfo.valid = true;
        addItemCellInfo.screen = addScreen;
        addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
        addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
        addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
        addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
        addItemCellInfo.findVacantCellsFromOccupied(
                savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS),
                savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X),
                savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y));
        mRestoring = true;
    }

    boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
    if (renameFolder) {
        long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
        mFolderInfo = sModel.getFolderById(this, id);
        mRestoring = true;
    }
}

From source file:com.tct.mail.ui.AbstractActivityController.java

/**
 * Restore the state from the previous bundle. Subclasses should call this
 * method from the parent class, since it performs important UI
 * initialization.//from ww  w. j  av  a2s  .  co  m
 *
 * @param savedState previous state
 */
@Override
public void onRestoreInstanceState(Bundle savedState) {
    mDetachedConvUri = savedState.getParcelable(SAVED_DETACHED_CONV_URI);
    if (savedState.containsKey(SAVED_CONVERSATION)) {
        // Open the conversation.
        final Conversation conversation = savedState.getParcelable(SAVED_CONVERSATION);
        if (conversation != null && conversation.position < 0) {
            // Set the position to 0 on this conversation, as we don't know where it is
            // in the list
            conversation.position = 0;
        }
        showConversation(conversation);
    }

    if (savedState.containsKey(SAVED_TOAST_BAR_OP)) {
        ToastBarOperation op = savedState.getParcelable(SAVED_TOAST_BAR_OP);
        if (op != null) {
            //TS: qing.liang 2015-03-10 EMAIL BUGFIX_-941849 ADD_S
            if (mConversationListCursor != null && mConversationListCursor.getUndoCallback() != null) {
                mUndoConversation = savedState.getParcelable(SAVED_UNDO_CONVERSATION);
                mUndoAction = savedState.getInt(SAVED_UNDO_ACTION);

                final UndoCallback undoCallback = new UndoCallback() {
                    @Override
                    public void performUndoCallback() {
                        showConversation(mUndoConversation);
                    }
                };
                mConversationListCursor.updateCallback(undoCallback);
            }
            //TS: qing.liang 2015-03-10 EMAIL BUGFIX_-941849 ADD_E
            if (op.getType() == ToastBarOperation.UNDO) {
                onUndoAvailable(op);
            } else if (op.getType() == ToastBarOperation.ERROR) {
                onError(mFolder, true);
            } else if (op.getType() == ToastBarOperation.DISCARD) { // TS: zheng.zou 2015-09-01 EMAIL BUGFIX-552138 ADD_S
                mSavedDraftMsgId = savedState.getLong(SAVED_DRAFT_MSG_ID);
                showDiscardDraftToast(mSavedDraftMsgId);
            } else if (op.getType() == ToastBarOperation.DISCARDED) {
                showDiscardedToast();
            }
            // TS: zheng.zou 2015-09-01 EMAIL BUGFIX-552138 ADD_E
        }
    }
    mFolderListFolder = savedState.getParcelable(SAVED_HIERARCHICAL_FOLDER);
    final ConversationListFragment convListFragment = getConversationListFragment();
    if (convListFragment != null) {
        convListFragment.getAnimatedAdapter().onRestoreInstanceState(savedState);
    }
    /*
     * Restore the state of selected conversations. This needs to be done after the correct mode
     * is set and the action bar is fully initialized. If not, several key pieces of state
     * information will be missing, and the split views may not be initialized correctly.
     */
    restoreSelectedConversations(savedState);
    // Order is important!!!
    // The dialog listener needs to happen *after* the selected set is restored.

    // If there has been an orientation change, and we need to recreate the listener for the
    // confirm dialog fragment (delete/archive/...), then do it here.
    if (mDialogAction != -1) {
        makeDialogListener(mDialogAction, mDialogFromSelectedSet,
                getUndoCallbackForDestructiveActionsWithAutoAdvance(mDialogAction, mCurrentConversation));
    }

    mInbox = savedState.getParcelable(SAVED_INBOX_KEY);

    mConversationListScrollPositions.clear();
    mConversationListScrollPositions.putAll(savedState.getBundle(SAVED_CONVERSATION_LIST_SCROLL_POSITIONS));
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //        // start following loader, does not use UI, but only gets a value to have ready for a menu action
    //        getSupportLoaderManager().initLoader(VNContract.Loaders.HIDDEN_VISITS, null, this);
    //Get a Tracker (should auto-report)
    ((VNApplication) getApplication()).getTracker(VNApplication.TrackerName.APP_TRACKER);
    // set up some default Preferences
    SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor prefEditor;
    if (!sharedPref.contains(Prefs.TARGET_ACCURACY_OF_VISIT_LOCATIONS)) {
        prefEditor = sharedPref.edit();// w w w .  ja  va2  s  .  c o m
        prefEditor.putFloat(Prefs.TARGET_ACCURACY_OF_VISIT_LOCATIONS, (float) 7.0);
        prefEditor.commit();
    }
    if (!sharedPref.contains(Prefs.TARGET_ACCURACY_OF_MAPPED_LOCATIONS)) {
        prefEditor = sharedPref.edit();
        prefEditor.putFloat(Prefs.TARGET_ACCURACY_OF_MAPPED_LOCATIONS, (float) 7.0);
        prefEditor.commit();
    }
    if (!sharedPref.contains(Prefs.UNIQUE_DEVICE_ID)) {
        prefEditor = sharedPref.edit();
        getUniqueDeviceId(this); // generate the ID and the source
        prefEditor.putString(Prefs.DEVICE_ID_SOURCE, mDeviceIdSource);
        prefEditor.putString(Prefs.UNIQUE_DEVICE_ID, mUniqueDeviceId);
        prefEditor.commit();
    }

    // Is there a description of what "local" is (e.g. "Iowa")? Initially, no
    if (!sharedPref.contains(Prefs.LOCAL_SPECIES_LIST_DESCRIPTION)) {
        prefEditor = sharedPref.edit();
        prefEditor.putString(Prefs.LOCAL_SPECIES_LIST_DESCRIPTION,
                this.getResources().getString(R.string.local_region_none));
        prefEditor.commit();
    }

    // Has the master species list been populated? As a default, assume not.
    if (!sharedPref.contains(Prefs.SPECIES_LIST_DOWNLOADED)) {
        prefEditor = sharedPref.edit();
        prefEditor.putBoolean(Prefs.SPECIES_LIST_DOWNLOADED, false);
        prefEditor.commit();
    }
    // start following loader, does not use UI, but tests if the master species list is populated
    getSupportLoaderManager().restartLoader(VNContract.Loaders.EXISTING_SPP, null, this);

    // Have the user verify each species entered as presence/absence? Initially, yes.
    // user will probably turn this one off each session, but turn it on on each restart
    prefEditor = sharedPref.edit();
    prefEditor.putBoolean(Prefs.VERIFY_VEG_ITEMS_PRESENCE, true);
    prefEditor.commit();

    // Set the default ID method to Digital Photograph
    if (!sharedPref.contains(Prefs.DEFAULT_IDENT_METHOD_ID)) {
        prefEditor = sharedPref.edit();
        prefEditor.putLong(Prefs.DEFAULT_IDENT_METHOD_ID, 1);
        prefEditor.commit();
    }

    // Set the default to allow species only once per subplot
    if (!sharedPref.contains(Prefs.SPECIES_ONCE)) {
        prefEditor = sharedPref.edit();
        prefEditor.putBoolean(Prefs.SPECIES_ONCE, true);
        prefEditor.commit();
    }

    // Set the default to use the "local species" feature
    if (!sharedPref.contains(Prefs.USE_LOCAL_SPP)) {
        prefEditor = sharedPref.edit();
        prefEditor.putBoolean(Prefs.USE_LOCAL_SPP, true);
        prefEditor.commit();
    }

    // Set if there is no "local" yet, use the default of not actually filtering for local species
    if (!sharedPref.contains(Prefs.LOCAL_SPP_CRIT)) {
        prefEditor = sharedPref.edit();
        prefEditor.putString(Prefs.LOCAL_SPP_CRIT, "%");
        prefEditor.commit();
    }

    // set up in-app billing
    // following resource is in it's own file, listed in .gitignore
    String base64EncodedPublicKey = getString(R.string.app_license);
    // set up the list of products, for now only donations
    mSkuCkList.add(SKU_DONATE_SMALL);
    mSkuCkList.add(SKU_DONATE_MEDIUM);
    mSkuCkList.add(SKU_DONATE_LARGE);
    mSkuCkList.add(SKU_DONATE_XLARGE);

    if (LDebug.ON)
        Log.d(LOG_TAG, "Creating IAB helper.");
    mHelper = new IabHelper(this, base64EncodedPublicKey);
    // enable debug logging (for production application, set this to false).
    mHelper.enableDebugLogging(LDebug.ON);
    // Start setup. This is asynchronous.
    // The specified listener will be called once setup completes.
    if (LDebug.ON)
        Log.d(LOG_TAG, "Starting setup.");
    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
        public void onIabSetupFinished(IabResult result) {
            if (LDebug.ON)
                Log.d(LOG_TAG, "Setup finished.");
            if (!result.isSuccess()) {
                // a problem.
                //Toast.makeText(this,
                //                        this.getResources().getString(R.string.in_app_bill_error) + result,
                //                        Toast.LENGTH_SHORT).show();
                return;
            }
            // disposed?
            if (mHelper == null)
                return;

            // always a good idea to query inventory
            // even if products were supposed to be consumed there might have been some glitch
            if (LDebug.ON)
                Log.d(LOG_TAG, "Setup done. Querying inventory.");
            mHelper.queryInventoryAsync(true, mSkuCkList, mGotInventoryListener);

        }
    });

    setContentView(R.layout.activity_vn_main);
    //      viewPager = (ViewPager) findViewById(R.id.data_entry_pager);
    //      FragmentManager fm = getSupportFragmentManager();
    //      viewPager.setAdapter(new dataPagerAdapter(fm));

    /* put conditions to test below
     * such as whether the container even exists in this layout
     * e.g. if (findViewById(R.id.fragment_container) != null)
     * */
    if (true) {
        if (savedInstanceState != null) {
            mVisitId = savedInstanceState.getLong(ARG_VISIT_ID);
            mConnectionRequested = savedInstanceState.getBoolean(ARG_CONNECTION_REQUESTED);
            mSubplotTypeId = savedInstanceState.getLong(ARG_SUBPLOT_TYPE_ID, 0);
            mNewPurcRecId = savedInstanceState.getLong(ARG_PURCH_REC_ID);
            // if restoring from a previous state, do not create view
            // could end up with overlapping views
            return;
        }

        // create an instance of New Visit fragment
        NewVisitFragment newVisitFrag = new NewVisitFragment();

        // in case this activity were started with special instructions from an Intent
        // pass the Intent's Extras to the fragment as arguments
        newVisitFrag.setArguments(getIntent().getExtras());

        // the tag is for the fragment now being added
        // it will stay with this fragment when put on the backstack
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fragment_container, newVisitFrag, Tags.NEW_VISIT);
        transaction.commit();
    }
}

From source file:com.adithya321.sharesanalysis.activities.MainActivity.java

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

    sharedPreferences = getSharedPreferences("prefs", 0);
    if (sharedPreferences.getBoolean("first", true)) {
        startActivity(new Intent(this, IntroActivity.class));
        return;/*  w  w w  .  j a  va 2s  . c  o m*/
    }

    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    AccountHeader accountHeader = new AccountHeaderBuilder().withHeaderBackground(R.drawable.header)
            .withCompactStyle(true).withActivity(this)
            .addProfiles(new ProfileDrawerItem().withName(sharedPreferences.getString("name", "Name"))
                    .withEmail("Target : " + sharedPreferences.getFloat("target", 20) + "%")
                    .withIcon(getResources().getDrawable(R.mipmap.ic_launcher)))
            .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
                @Override
                public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
                    return false;
                }
            }).build();

    final DatabaseHandler databaseHandler = new DatabaseHandler(getApplicationContext());

    drawer = new DrawerBuilder().withActivity(this).withToolbar(toolbar).withAccountHeader(accountHeader)
            .withActionBarDrawerToggleAnimated(true)
            .addDrawerItems(
                    new PrimaryDrawerItem().withIdentifier(0).withName("Dashboard")
                            .withIcon(R.drawable.ic_timeline_gray),
                    new PrimaryDrawerItem().withIdentifier(1).withName("Fund Flow")
                            .withIcon(R.drawable.ic_compare_arrows_gray),
                    new DividerDrawerItem(),
                    new PrimaryDrawerItem().withIdentifier(2).withName("Share Purchase")
                            .withIcon(R.drawable.ic_add_red)
                            .withTextColor(getResources().getColor(R.color.red_500)),
                    new PrimaryDrawerItem().withIdentifier(3).withName("Share Sales")
                            .withIcon(R.drawable.ic_remove_green)
                            .withTextColor(getResources().getColor(R.color.colorPrimary)),
                    new PrimaryDrawerItem().withIdentifier(4).withName("Share Holdings")
                            .withIcon(R.drawable.ic_account_balance_blue)
                            .withTextColor(getResources().getColor(R.color.colorAccent)),
                    new DividerDrawerItem(),
                    new PrimaryDrawerItem().withIdentifier(5).withName("Charts")
                            .withIcon(R.drawable.ic_insert_chart_gray),
                    new PrimaryDrawerItem()
                            .withIdentifier(6).withName("Summary").withIcon(R.drawable.ic_description_gray),
                    new DividerDrawerItem(),
                    new PrimaryDrawerItem().withIdentifier(7).withName("Feedback")
                            .withIcon(R.drawable.ic_feedback_gray),
                    new PrimaryDrawerItem()
                            .withIdentifier(8).withName("Help").withIcon(R.drawable.ic_help_gray),
                    new DividerDrawerItem(),
                    new PrimaryDrawerItem().withIdentifier(10).withName("Backup")
                            .withIcon(R.drawable.ic_backup_gray),
                    new PrimaryDrawerItem()
                            .withIdentifier(11).withName("Restore").withIcon(R.drawable.ic_restore_gray),
                    new DividerDrawerItem(),
                    new PrimaryDrawerItem().withIdentifier(21).withName("Settings")
                            .withIcon(R.drawable.ic_settings_gray),
                    new PrimaryDrawerItem().withIdentifier(22).withName("About")
                            .withIcon(R.drawable.ic_info_gray))
            .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override
                public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                    boolean flag;
                    List<Share> shareList = databaseHandler.getShares();
                    if (drawerItem != null) {
                        flag = true;
                        switch ((int) drawerItem.getIdentifier()) {
                        case 0:
                            if (shareList.size() < 1)
                                drawer.setSelection(2, true);
                            else
                                switchFragment("Dashboard", "Dashboard");
                            break;
                        case 1:
                            switchFragment("Fund Flow", "FundFlow");
                            break;

                        case 2:
                            switchFragment("Share Purchase", "SharePurchaseMain");
                            break;
                        case 3:
                            if (shareList.size() < 1)
                                drawer.setSelection(2, true);
                            else
                                switchFragment("Share Sales", "SharePurchaseMain");
                            break;
                        case 4:
                            if (shareList.size() < 1)
                                drawer.setSelection(2, true);
                            else
                                switchFragment("Share Holdings", "ShareHoldings");
                            break;

                        case 5:
                            if (shareList.size() < 1)
                                drawer.setSelection(2, true);
                            else
                                switchFragment("Charts", "Charts");
                            break;
                        case 6:
                            if (shareList.size() < 1)
                                drawer.setSelection(2, true);
                            else
                                switchFragment("Summary", "Summary");
                            break;

                        case 7:
                            ConversationActivity.show(MainActivity.this);
                            break;
                        case 8:
                            startActivity(new Intent(MainActivity.this, IntroActivity.class));
                            break;

                        case 10:
                            RealmBackupRestore backup = new RealmBackupRestore(MainActivity.this);
                            backup.backup();
                            break;
                        case 11:
                            RealmBackupRestore restore = new RealmBackupRestore(MainActivity.this);
                            restore.restore();
                            Intent mStartActivity = new Intent(MainActivity.this, MainActivity.class);
                            int mPendingIntentId = 123456;
                            PendingIntent mPendingIntent = PendingIntent.getActivity(MainActivity.this,
                                    mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
                            AlarmManager mgr = (AlarmManager) MainActivity.this
                                    .getSystemService(Context.ALARM_SERVICE);
                            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
                            System.exit(0);
                            break;

                        case 21:
                            startActivity(new Intent(MainActivity.this, ProfileActivity.class));
                            break;
                        case 22:
                            new LibsBuilder().withActivityStyle(Libs.ActivityStyle.LIGHT_DARK_TOOLBAR)
                                    .withActivityTitle(getString(R.string.app_name)).withAboutIconShown(true)
                                    .withAboutVersionShown(true).withVersionShown(true).withLicenseShown(true)
                                    .withLicenseDialog(true).withListener(libsListener)
                                    .start(MainActivity.this);
                            break;

                        default:
                            switchFragment("Dashboard", "Dashboard");
                            break;
                        }
                    } else {
                        flag = false;
                    }
                    return flag;
                }
            }).build();

    if (savedInstanceState == null)
        drawer.setSelection(0, true);
    else
        drawer.setSelection(savedInstanceState.getLong("drawerSelection"), true);

    CustomActivityOnCrash.install(this);
}