Example usage for android.os Bundle getBoolean

List of usage examples for android.os Bundle getBoolean

Introduction

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

Prototype

public boolean getBoolean(String key, boolean defaultValue) 

Source Link

Document

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

Usage

From source file:com.grass.caishi.cc.activity.main.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) {
        // ??home???appcrash
        // fragment??
        MyApplication.getInstance().logout(null);
        finish();/*from w  w  w  . j  a  v a2  s .c  o m*/
        startActivity(new Intent(this, LoginActivity.class));
        return;
    } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
        // T??home???appcrash
        // fragment??
        finish();
        startActivity(new Intent(this, LoginActivity.class));
        return;
    }

    hideNavigationBar();

    setContentView(R.layout.activity_main);
    initView();
    try {
        add_code = Integer.valueOf(PreferenceUtils.getInstance(this).getSettingUserCityCode());
        //TODO ??
        android.util.Log.e("kevin", "mainActivity:" + add_code);

    } catch (Exception e) {
        //
    }
    if (getIntent().getBooleanExtra("conflict", false) && !isConflictDialogShow) {
        showConflictDialog();
    } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) {
        showAccountRemovedDialog();
    }

    inviteMessgeDao = new InviteMessgeDao(this);
    userDao = new UserDao(this);

    selectCityFrament = new SelectCityFragment();
    selectMainFrament = new SelectMainFragment();
    // fragment???
    // chatHistoryFragment = new ChatHistoryFragment();
    // ?fragment
    chatMessageFragment = new ChatMessageFragment();
    friendsListFragment = new FriendsListFragment();
    settingFragment = new SettingsFragment();
    fragments = new Fragment[] { chatMessageFragment, selectCityFrament, selectMainFrament, friendsListFragment,
            settingFragment };

    getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, chatMessageFragment)
            .add(R.id.fragment_container, friendsListFragment).hide(friendsListFragment)
            .show(chatMessageFragment).commit();

    init();

    // refreshFriends();
    mainLoad();

    new Thread(new Runnable() {
        @Override
        public void run() {
            //
            deleteAllFiles(StorageUtils.getOwnCacheDirectory(MainActivity.this, Constant.CACHE_DIR_IMAGE));
        }
    }).start();
    if (!getIntent().getBooleanExtra("login", false)) {
        refreshFriends();
    }

    findViewById(R.id.btn_main_circle_community).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            startActivity(new Intent(MainActivity.this, TimeListActivity.class));
        }
    });

    android.util.Log.e("kevin", "useid" + MyApplication.getInstance().getUserID());

}

From source file:com.android.incallui.CallCardFragment.java

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

    mHandler = new Handler(Looper.getMainLooper());
    mShrinkAnimationDuration = getResources().getInteger(R.integer.shrink_animation_duration);
    mVideoAnimationDuration = getResources().getInteger(R.integer.video_animation_duration);
    mFloatingActionButtonVerticalOffset = getResources()
            .getDimensionPixelOffset(R.dimen.floating_action_button_vertical_offset);
    mFabNormalDiameter = getResources()// ww w . j a v  a 2 s .  co m
            .getDimensionPixelOffset(R.dimen.end_call_floating_action_button_diameter);
    mFabSmallDiameter = getResources()
            .getDimensionPixelOffset(R.dimen.end_call_floating_action_button_small_diameter);

    if (savedInstanceState != null) {
        mIsDialpadShowing = savedInstanceState.getBoolean(IS_DIALPAD_SHOWING_KEY, false);
    }
}

From source file:cn.kangeqiu.kq.activity.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null)
        mContent = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
    if (mContent == null)
        mContent = new FragmentMatch(R.color.red);
    // set the Above View
    setContentView(R.layout.content_frame);
    getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent).commit();
    // set the Behind View
    setBehindContentView(R.layout.menu_frame);
    menuFragment = new MenuFragment();
    personFragment = new MineActivity();
    getSupportFragmentManager().beginTransaction().replace(R.id.menu_frame, menuFragment).commit();
    // customize the SlidingMenu
    getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
    context = this;
    if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) {
        // ??home???appcrash
        // fragment??
        BaseApplication.getInstance().logout(null);
        finish();/*w  w  w . j  av a 2  s . c  o m*/
        startActivity(new Intent(this, LoginActivity.class));
        return;
    } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
        // T??home???appcrash
        // fragment??
        finish();
        startActivity(new Intent(this, LoginActivity.class));
        return;
    }
    setContentView(R.layout.activity_main);
    initView();

    // MobclickAgent.setDebugMode( true );
    // --?--
    // MobclickAgent.updateOnlineConfig(this);

    if (getIntent().getBooleanExtra("conflict", false) && !isConflictDialogShow) {
        showConflictDialog();
    } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) {
        showAccountRemovedDialog();
    }

    inviteMessgeDao = new InviteMessgeDao(this);
    userDao = new UserDao(this);
    // fragment???
    // chatHistoryFragment = new ChatHistoryFragment();
    // ?fragment
    chatHistoryFragment = new ChatAllHistoryFragment();
    // contactListFragment = new ContactlistFragment();
    // settingFragment = new SettingsFragment();
    teamFragment = new FragmentMatch();
    dataFragment = new FragmentData();
    // nearbyFragment = new FragmentNearbyNew();
    // finderFragment = new FragmentFinder();
    // fragments = new Fragment[] { chatHistoryFragment,
    // nearbyFragment,finderFragment, teamFragment, personFragment };
    fragments = new Fragment[] { teamFragment, chatHistoryFragment, dataFragment, personFragment };
    // fragment
    // getSupportFragmentManager().beginTransaction()
    // .add(R.id.fragment_container, teamFragment).show(teamFragment)
    // .commit();

    // getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,
    // chatHistoryFragment)
    // .add(R.id.fragment_container,
    // contactListFragment).hide(contactListFragment).show(chatHistoryFragment).commit();

    // ?BroadcastReceiver
    msgReceiver = new NewMessageBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
    intentFilter.setPriority(3);
    registerReceiver(msgReceiver, intentFilter);

    // ack?BroadcastReceiver
    IntentFilter ackMessageIntentFilter = new IntentFilter(
            EMChatManager.getInstance().getAckMessageBroadcastAction());
    ackMessageIntentFilter.setPriority(3);
    registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

    // ??BroadcastReceiver
    IntentFilter cmdMessageIntentFilter = new IntentFilter(
            EMChatManager.getInstance().getCmdMessageBroadcastAction());
    cmdMessageIntentFilter.setPriority(3);
    registerReceiver(cmdMessageReceiver, cmdMessageIntentFilter);

    // ?BroadcastReceiver
    // IntentFilter offlineMessageIntentFilter = new
    // IntentFilter(EMChatManager.getInstance()
    // .getOfflineMessageBroadcastAction());
    // registerReceiver(offlineMessageReceiver, offlineMessageIntentFilter);

    // setContactListener???
    // EMContactManager.getInstance().setContactListener(
    // new MyContactListener());
    // ??listener
    // EMChatManager.getInstance().addConnectionListener(
    // new MyConnectionListener());
    // ?listener
    // EMGroupManager.getInstance().addGroupChangeListener(
    // new MyGroupChangeListener());
    // sdkUI ??receiverlistener, ??broadcast
    EMChat.getInstance().setAppInited();

    // ??
    // initBaiduLocation();
}

From source file:com.android.music.TrackBrowserFragment.java

/** Called when the activity is first created. */

@Override//w w  w . j  a v a  2 s  .c  o m
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater.inflate(R.layout.media_picker_activity, null);

    Intent intent = getActivity().getIntent();
    /*if (intent != null) {
     if (intent.getBooleanExtra("withtabs", false)) {
        getActivity().requestWindowFeature(Window.FEATURE_NO_TITLE);
     }
    }*/
    getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
    if (savedInstanceState != null) {
        mSelectedId = savedInstanceState.getLong("selectedtrack");
        mAlbumId = savedInstanceState.getString("album");
        mArtistId = savedInstanceState.getString("artist");
        mPlaylist = savedInstanceState.getString("playlist");
        mGenre = savedInstanceState.getString("genre");
        mEditMode = savedInstanceState.getBoolean("editmode", false);
    } else {
        mAlbumId = intent.getStringExtra("album");
        // If we have an album, show everything on the album, not just stuff
        // by a particular artist.
        mArtistId = intent.getStringExtra("artist");
        mPlaylist = intent.getStringExtra("playlist");
        mGenre = intent.getStringExtra("genre");
        mEditMode = intent.getAction().equals(Intent.ACTION_EDIT);
    }

    mCursorCols = new String[] { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.DURATION };
    mPlaylistMemberCols = new String[] { MediaStore.Audio.Playlists.Members._ID, MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Playlists.Members.PLAY_ORDER, MediaStore.Audio.Playlists.Members.AUDIO_ID,
            MediaStore.Audio.Media.IS_MUSIC };

    //mUseLastListPos = MusicUtils.updateButtonBar(getActivity(), R.id.songtab);
    mTrackList = (ListView) view.findViewById(android.R.id.list);
    mTrackList.setOnCreateContextMenuListener(this);
    mTrackList.setCacheColorHint(0);
    if (mEditMode) {
        ((TouchInterceptor) mTrackList).setDropListener(mDropListener);
        ((TouchInterceptor) mTrackList).setRemoveListener(mRemoveListener);
        mTrackList.setDivider(null);
        mTrackList.setSelector(R.drawable.list_selector_background);
    } else {
        mTrackList.setTextFilterEnabled(true);
    }
    mAdapter = (TrackListAdapter) getActivity().getLastNonConfigurationInstance();

    if (mAdapter != null) {
        mAdapter.setActivity(this);
        mTrackList.setAdapter(mAdapter);
    }
    mToken = MusicUtils.bindToService(getActivity(), this);

    // don't set the album art until after the view has been layed out
    mTrackList.post(new Runnable() {

        public void run() {
            setAlbumArtBackground();
        }
    });

    // mTrackList.dispatchKeyEvent();

    mTrackList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            if (mTrackCursor.getCount() == 0) {
                return;
            }
            // When selecting a track from the queue, just jump there instead of
            // reloading the queue. This is both faster, and prevents accidentally
            // dropping out of party shuffle.
            if (mTrackCursor instanceof NowPlayingCursor) {
                if (MusicUtils.sService != null) {
                    try {
                        MusicUtils.sService.setQueuePosition(position);
                        return;
                    } catch (RemoteException ex) {
                    }
                }
            }
            MusicUtils.playAll(getActivity(), mTrackCursor, position);

        }
    });

    return view;
}

From source file:com.ifeel.healthy.SelectionFragment.java

/**
 * Resets the view to the initial defaults.
 *//*  w ww  . j a va  2 s. c om*/
private void init(Bundle savedInstanceState) {
    announceButton.setEnabled(false);
    messageButton.setEnabled(false);

    listElements = new ArrayList<BaseListElement>();

    //listElements.add(new EatListElement(0));
    //listElements.add(new LocationListElement(1));
    //listElements.add(new PeopleListElement(2));
    //listElements.add(new PhotoListElement(3));

    listElements.add(new MindfulBreadingListElement(0));
    listElements.add(new SessionListElement(1));
    listElements.add(new PracticePartnerListElement(2));
    listElements.add(new HistoryGraphListElement(3));
    listElements.add(new InstructionListElement(4));
    listElements.add(new PurchaseListElement(4));

    if (savedInstanceState != null) {
        for (BaseListElement listElement : listElements) {
            listElement.restoreState(savedInstanceState);
        }
        pendingAnnounce = savedInstanceState.getBoolean(PENDING_ANNOUNCE_KEY, false);
    }

    listView.setAdapter(new ActionListAdapter(getActivity(), R.id.selection_list, listElements));

    Session session = Session.getActiveSession();
    if (session != null && session.isOpened()) {
        makeMeRequest(session);
    }
}

From source file:edu.mit.mobile.android.locast.sync.SyncEngine.java

/**
 * @param toSync//w  w w .  jav a 2 s  . c  o m
 * @param account
 * @param extras
 * @param provider
 * @param syncResult
 * @return true if the item was sync'd successfully. Soft errors will cause this to return
 *         false.
 * @throws RemoteException
 * @throws SyncException
 * @throws JSONException
 * @throws IOException
 * @throws NetworkProtocolException
 * @throws NoPublicPath
 * @throws OperationApplicationException
 * @throws InterruptedException
 */
public boolean sync(Uri toSync, Account account, Bundle extras, ContentProviderClient provider,
        SyncResult syncResult) throws RemoteException, SyncException, JSONException, IOException,
        NetworkProtocolException, NoPublicPath, OperationApplicationException, InterruptedException {

    String pubPath = null;

    //
    // Handle http or https uris separately. These require the
    // destination uri.
    //
    if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) {
        pubPath = toSync.toString();

        if (!extras.containsKey(EXTRA_DESTINATION_URI)) {
            throw new IllegalArgumentException("missing EXTRA_DESTINATION_URI when syncing HTTP URIs");
        }
        toSync = Uri.parse(extras.getString(EXTRA_DESTINATION_URI));
    }

    final String type = provider.getType(toSync);
    final boolean isDir = type.startsWith(CONTENT_TYPE_PREFIX_DIR);

    final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);

    // skip any items already sync'd
    if (!manualSync && mLastUpdated.isUpdatedRecently(toSync)) {
        if (DEBUG) {
            Log.d(TAG, "not syncing " + toSync + " as it's been updated recently");
        }
        syncResult.stats.numSkippedEntries++;
        return false;
    }

    // the sync map will convert the json data to ContentValues
    final SyncMap syncMap = MediaProvider.getSyncMap(provider, toSync);

    final Uri toSyncWithoutQuerystring = toSync.buildUpon().query(null).build();

    final HashMap<String, SyncStatus> syncStatuses = new HashMap<String, SyncEngine.SyncStatus>();
    final ArrayList<ContentProviderOperation> cpo = new ArrayList<ContentProviderOperation>();
    final LinkedList<String> cpoPubUris = new LinkedList<String>();

    //
    // first things first, upload any content that needs to be
    // uploaded.
    //

    try {
        uploadUnpublished(toSync, account, provider, syncMap, syncStatuses, syncResult);

        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        // this should ensure that all items have a pubPath when we
        // query it below.

        if (pubPath == null) {
            // we should avoid calling this too much as it
            // can be expensive
            pubPath = MediaProvider.getPublicPath(mContext, toSync);
        }
    } catch (final NoPublicPath e) {
        // TODO this is a special case and this is probably not the best place to handle this.
        // Ideally, this should be done in such a way as to reduce any extra DB queries -
        // perhaps by doing a join with the parent.
        if (syncMap.isFlagSet(SyncMap.FLAG_PARENT_MUST_SYNC_FIRST)) {
            if (DEBUG) {
                Log.d(TAG, "skipping " + toSync + " whose parent hasn't been sync'd first");
            }
            syncResult.stats.numSkippedEntries++;
            return false;
        }

        // if it's an item, we can handle it.
        if (isDir) {
            throw e;
        }
    }

    if (pubPath == null) {

        // this should have been updated already by the initial
        // upload, so something must be wrong
        throw new SyncException("never got a public path for " + toSync);
    }

    if (DEBUG) {
        Log.d(TAG, "sync(toSync=" + toSync + ", account=" + account + ", extras=" + extras + ", manualSync="
                + manualSync + ",...)");
        Log.d(TAG, "pubPath: " + pubPath);
    }

    final long request_time = System.currentTimeMillis();

    HttpResponse hr = mNetworkClient.get(pubPath);

    final long response_time = System.currentTimeMillis();

    // the time compensation below allows a time-based synchronization to function even if the
    // local clock is entirely wrong. The server's time is extracted using the Date header and
    // all are compared relative to the respective clock reference. Any data that's stored on
    // the mobile should be stored relative to the local clock and the server will respect the
    // same.
    long serverTime;

    try {
        serverTime = getServerTime(hr);
    } catch (final DateParseException e) {
        Log.w(TAG, "could not retrieve date from server. Using local time, which may be incorrect.", e);
        serverTime = System.currentTimeMillis();
    }

    // TODO check out
    // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
    final long response_delay = response_time - request_time;
    if (DEBUG) {
        Log.d(TAG, "request took " + response_delay + "ms");
    }
    final long localTime = request_time;

    // add this to the server time to get the local time
    final long localOffset = (localTime - serverTime);

    if (Math.abs(localOffset) > 30 * 60 * 1000) {
        Log.w(TAG, "local clock is off by " + localOffset + "ms");
    }

    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    final HttpEntity ent = hr.getEntity();

    String selection;
    String selectionInverse;
    String[] selectionArgs;

    if (isDir) {

        final JSONArray ja = new JSONArray(StreamUtils.inputStreamToString(ent.getContent()));
        ent.consumeContent();

        final int len = ja.length();
        selectionArgs = new String[len];

        // build the query to see which items are already in the
        // database
        final StringBuilder sb = new StringBuilder();

        sb.append("(");

        for (int i = 0; i < len; i++) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final SyncStatus syncStatus = loadItemFromJsonObject(ja.getJSONObject(i), syncMap, serverTime);

            syncStatuses.put(syncStatus.remote, syncStatus);

            selectionArgs[i] = syncStatus.remote;

            // add in a placeholder for the query
            sb.append('?');
            if (i != (len - 1)) {
                sb.append(',');
            }

        }
        sb.append(")");

        final String placeholders = sb.toString();
        selection = JsonSyncableItem._PUBLIC_URI + " IN " + placeholders;
        selectionInverse = JsonSyncableItem._PUBLIC_URI + " NOT IN " + placeholders;
    } else {

        final JSONObject jo = new JSONObject(StreamUtils.inputStreamToString(ent.getContent()));
        ent.consumeContent();
        final SyncStatus syncStatus = loadItemFromJsonObject(jo, syncMap, serverTime);

        syncStatuses.put(syncStatus.remote, syncStatus);

        selection = JsonSyncableItem._PUBLIC_URI + "=?";
        selectionInverse = JsonSyncableItem._PUBLIC_URI + "!=?";
        selectionArgs = new String[] { syncStatus.remote };
    }

    // first check without the querystring. This will ensure that we
    // properly mark things that we already have in the database.
    final Cursor check = provider.query(toSyncWithoutQuerystring, SYNC_PROJECTION, selection, selectionArgs,
            null);

    // these items are on both sides
    try {
        final int pubUriCol = check.getColumnIndex(JsonSyncableItem._PUBLIC_URI);
        final int idCol = check.getColumnIndex(JsonSyncableItem._ID);

        // All the items in this cursor should be found on both
        // the client and the server.
        for (check.moveToFirst(); !check.isAfterLast(); check.moveToNext()) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final long id = check.getLong(idCol);
            final Uri localUri = ContentUris.withAppendedId(toSync, id);

            final String pubUri = check.getString(pubUriCol);

            final SyncStatus itemStatus = syncStatuses.get(pubUri);

            itemStatus.state = SyncState.BOTH_UNKNOWN;

            itemStatus.local = localUri;

            // make the status searchable by both remote and
            // local uri
            syncStatuses.put(localUri.toString(), itemStatus);
        }
    } finally {
        check.close();
    }

    Cursor c = provider.query(toSync, SYNC_PROJECTION, selection, selectionArgs, null);

    // these items are on both sides
    try {
        final int pubUriCol = c.getColumnIndex(JsonSyncableItem._PUBLIC_URI);
        final int localModifiedCol = c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE);
        final int serverModifiedCol = c.getColumnIndex(JsonSyncableItem._SERVER_MODIFIED_DATE);
        final int idCol = c.getColumnIndex(JsonSyncableItem._ID);

        // All the items in this cursor should be found on both
        // the client and the server.
        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final long id = c.getLong(idCol);
            final Uri localUri = ContentUris.withAppendedId(toSync, id);

            final String pubUri = c.getString(pubUriCol);

            final SyncStatus itemStatus = syncStatuses.get(pubUri);

            if (itemStatus.state == SyncState.ALREADY_UP_TO_DATE
                    || itemStatus.state == SyncState.NOW_UP_TO_DATE) {
                if (DEBUG) {
                    Log.d(TAG, localUri + "(" + pubUri + ")" + " is already up to date.");
                }
                continue;
            }

            itemStatus.local = localUri;

            // make the status searchable by both remote and local uri
            syncStatuses.put(localUri.toString(), itemStatus);

            // last modified as stored in the DB, in phone time
            final long itemLocalModified = c.getLong(localModifiedCol);

            // last modified as stored in the DB, in server time
            final long itemServerModified = c.getLong(serverModifiedCol);
            final long localAge = localTime - itemLocalModified;

            final long remoteAge = serverTime - itemStatus.remoteModifiedTime;

            final long ageDifference = Math.abs(localAge - remoteAge);

            // up to date, as far remote -> local goes
            if (itemServerModified == itemStatus.remoteModifiedTime) {
                itemStatus.state = SyncState.ALREADY_UP_TO_DATE;
                if (DEBUG) {
                    Log.d(TAG, pubUri + " is up to date.");
                }

                // need to download
            } else if (localAge > remoteAge) {
                if (DEBUG) {
                    final long serverModified = itemStatus.remoteModifiedTime;

                    Log.d(TAG,
                            pubUri + " : local is " + ageDifference + "ms older ("
                                    + android.text.format.DateUtils.formatDateTime(mContext, itemLocalModified,
                                            FORMAT_ARGS_DEBUG)
                                    + ") than remote (" + android.text.format.DateUtils.formatDateTime(mContext,
                                            serverModified, FORMAT_ARGS_DEBUG)
                                    + "); updating local copy...");
                }

                itemStatus.state = SyncState.REMOTE_DIRTY;

                final ContentProviderOperation.Builder b = ContentProviderOperation.newUpdate(localUri);

                // update this so it's in the local timescale
                correctServerOffset(itemStatus.remoteCVs, JsonSyncableItem._CREATED_DATE,
                        JsonSyncableItem._CREATED_DATE, localOffset);
                correctServerOffset(itemStatus.remoteCVs, JsonSyncableItem._SERVER_MODIFIED_DATE,
                        JsonSyncableItem._MODIFIED_DATE, localOffset);

                b.withValues(itemStatus.remoteCVs);
                b.withExpectedCount(1);

                cpo.add(b.build());
                cpoPubUris.add(pubUri);

                syncResult.stats.numUpdates++;

                // need to upload
            } else if (localAge < remoteAge) {
                if (DEBUG) {
                    final long serverModified = itemStatus.remoteModifiedTime;

                    Log.d(TAG,
                            pubUri + " : local is " + ageDifference + "ms newer ("
                                    + android.text.format.DateUtils.formatDateTime(mContext, itemLocalModified,
                                            FORMAT_ARGS_DEBUG)
                                    + ") than remote (" + android.text.format.DateUtils.formatDateTime(mContext,
                                            serverModified, FORMAT_ARGS_DEBUG)
                                    + "); publishing to server...");
                }
                itemStatus.state = SyncState.LOCAL_DIRTY;

                mNetworkClient.putJson(pubPath, JsonSyncableItem.toJSON(mContext, localUri, c, syncMap));
            }

            mLastUpdated.markUpdated(localUri);

            syncResult.stats.numEntries++;
        } // end for
    } finally {

        c.close();
    }

    /*
     * Apply updates in bulk
     */
    if (cpo.size() > 0) {
        if (DEBUG) {
            Log.d(TAG, "applying " + cpo.size() + " bulk updates...");
        }

        final ContentProviderResult[] r = provider.applyBatch(cpo);
        if (DEBUG) {
            Log.d(TAG, "Done applying updates. Running postSync handler...");
        }

        for (int i = 0; i < r.length; i++) {
            final ContentProviderResult res = r[i];
            final SyncStatus ss = syncStatuses.get(cpoPubUris.get(i));
            if (ss == null) {
                Log.e(TAG, "can't get sync status for " + res.uri);
                continue;
            }
            syncMap.onPostSyncItem(mContext, account, ss.local, ss.remoteJson,
                    res.count != null ? res.count == 1 : true);

            ss.state = SyncState.NOW_UP_TO_DATE;
        }

        if (DEBUG) {
            Log.d(TAG, "done running postSync handler.");
        }

        cpo.clear();
        cpoPubUris.clear();
    }

    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    /*
     * Look through the SyncState.state values and find ones that need to be stored.
     */

    for (final Map.Entry<String, SyncStatus> entry : syncStatuses.entrySet()) {
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        final String pubUri = entry.getKey();
        final SyncStatus status = entry.getValue();
        if (status.state == SyncState.REMOTE_ONLY) {
            if (DEBUG) {
                Log.d(TAG, pubUri + " is not yet stored locally, adding...");
            }

            // update this so it's in the local timescale
            correctServerOffset(status.remoteCVs, JsonSyncableItem._CREATED_DATE,
                    JsonSyncableItem._CREATED_DATE, localOffset);
            correctServerOffset(status.remoteCVs, JsonSyncableItem._SERVER_MODIFIED_DATE,
                    JsonSyncableItem._MODIFIED_DATE, localOffset);

            final ContentProviderOperation.Builder b = ContentProviderOperation.newInsert(toSync);
            b.withValues(status.remoteCVs);

            cpo.add(b.build());
            cpoPubUris.add(pubUri);
            syncResult.stats.numInserts++;

        }
    }

    /*
     * Execute the content provider operations in bulk.
     */
    if (cpo.size() > 0) {
        if (DEBUG) {
            Log.d(TAG, "bulk inserting " + cpo.size() + " items...");
        }
        final ContentProviderResult[] r = provider.applyBatch(cpo);
        if (DEBUG) {
            Log.d(TAG, "applyBatch completed. Processing results...");
        }

        int successful = 0;
        for (int i = 0; i < r.length; i++) {
            final ContentProviderResult res = r[i];
            if (res.uri == null) {
                syncResult.stats.numSkippedEntries++;
                Log.e(TAG, "result from content provider bulk operation returned null");
                continue;
            }
            final String pubUri = cpoPubUris.get(i);
            final SyncStatus ss = syncStatuses.get(pubUri);

            if (ss == null) {
                syncResult.stats.numSkippedEntries++;
                Log.e(TAG, "could not find sync status for " + cpoPubUris.get(i));
                continue;
            }

            ss.local = res.uri;
            if (DEBUG) {
                Log.d(TAG, "onPostSyncItem(" + res.uri + ", ...); pubUri: " + pubUri);
            }

            syncMap.onPostSyncItem(mContext, account, res.uri, ss.remoteJson,
                    res.count != null ? res.count == 1 : true);

            ss.state = SyncState.NOW_UP_TO_DATE;
            successful++;
        }
        if (DEBUG) {
            Log.d(TAG, successful + " batch inserts successfully applied.");
        }
    } else {
        if (DEBUG) {
            Log.d(TAG, "no updates to perform.");
        }
    }

    /**
     * Look through all the items that we didn't already find on the server side, but which
     * still have a public uri. They should be checked to make sure they're not deleted.
     */
    c = provider.query(toSync, SYNC_PROJECTION,
            ProviderUtils.addExtraWhere(selectionInverse, JsonSyncableItem._PUBLIC_URI + " NOT NULL"),
            selectionArgs, null);

    try {
        final int idCol = c.getColumnIndex(JsonSyncableItem._ID);
        final int pubUriCol = c.getColumnIndex(JsonSyncableItem._PUBLIC_URI);

        cpo.clear();

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            final String pubUri = c.getString(pubUriCol);
            SyncStatus ss = syncStatuses.get(pubUri);

            final Uri item = isDir ? ContentUris.withAppendedId(toSyncWithoutQuerystring, c.getLong(idCol))
                    : toSync;

            if (ss == null) {
                ss = syncStatuses.get(item.toString());
            }

            if (DEBUG) {
                Log.d(TAG, item + " was not found in the main list of items on the server (" + pubPath
                        + "), but appears to be a child of " + toSync);

                if (ss != null) {
                    Log.d(TAG, "found sync status for " + item + ": " + ss);
                }
            }

            if (ss != null) {
                switch (ss.state) {
                case ALREADY_UP_TO_DATE:
                case NOW_UP_TO_DATE:
                    if (DEBUG) {
                        Log.d(TAG, item + " is already up to date. No need to see if it was deleted.");
                    }
                    continue;

                case BOTH_UNKNOWN:
                    if (DEBUG) {
                        Log.d(TAG,
                                item + " was found on both sides, but has an unknown sync status. Skipping...");
                    }
                    continue;

                default:

                    Log.w(TAG, "got an unexpected state for " + item + ": " + ss);
                }

            } else {
                ss = new SyncStatus(pubUri, SyncState.LOCAL_ONLY);
                ss.local = item;

                hr = mNetworkClient.head(pubUri);

                switch (hr.getStatusLine().getStatusCode()) {
                case 200:
                    if (DEBUG) {
                        Log.d(TAG, "HEAD " + pubUri + " returned 200");
                    }
                    ss.state = SyncState.BOTH_UNKNOWN;
                    break;

                case 404:
                    if (DEBUG) {
                        Log.d(TAG, "HEAD " + pubUri + " returned 404. Deleting locally...");
                    }
                    ss.state = SyncState.DELETED_REMOTELY;
                    final ContentProviderOperation deleteOp = ContentProviderOperation
                            .newDelete(ContentUris.withAppendedId(toSyncWithoutQuerystring, c.getLong(idCol)))
                            .build();
                    cpo.add(deleteOp);

                    break;

                default:
                    syncResult.stats.numIoExceptions++;
                    Log.w(TAG, "HEAD " + pubUri + " got unhandled result: " + hr.getStatusLine());
                }
            }
            syncStatuses.put(pubUri, ss);
        } // for cursor

        if (cpo.size() > 0) {
            final ContentProviderResult[] results = provider.applyBatch(cpo);

            for (final ContentProviderResult result : results) {
                if (result.count != 1) {
                    throw new SyncException("Error deleting item");
                }
            }
        }

    } finally {
        c.close();
    }

    syncStatuses.clear();

    mLastUpdated.markUpdated(toSync);

    return true;
}

From source file:com.android.tv.settings.dialog.DialogFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    android.util.Log.v("DialogFragment", "onCreate");
    super.onCreate(savedInstanceState);
    Bundle state = (savedInstanceState != null) ? savedInstanceState : getArguments();
    if (mTitle == null) {
        mTitle = state.getString(EXTRA_CONTENT_TITLE);
    }/*from  w  w  w . ja  va2 s .  co m*/
    if (mBreadcrumb == null) {
        mBreadcrumb = state.getString(EXTRA_CONTENT_BREADCRUMB);
    }
    if (mDescription == null) {
        mDescription = state.getString(EXTRA_CONTENT_DESCRIPTION);
    }
    if (mIconResourceId == 0) {
        mIconResourceId = state.getInt(EXTRA_CONTENT_ICON_RESOURCE_ID, 0);
    }
    if (mIconUri == null) {
        mIconUri = state.getParcelable(EXTRA_CONTENT_ICON_URI);
    }
    if (mIconBitmap == null) {
        mIconBitmap = state.getParcelable(EXTRA_CONTENT_ICON_BITMAP);
    }
    if (mIconBackgroundColor == Color.TRANSPARENT) {
        mIconBackgroundColor = state.getInt(EXTRA_CONTENT_ICON_BACKGROUND, Color.TRANSPARENT);
    }
    if (mActions == null) {
        mActions = state.getParcelableArrayList(EXTRA_ACTION_ACTIONS);
    }
    if (mName == null) {
        mName = state.getString(EXTRA_ACTION_NAME);
    }
    if (mSelectedIndex == -1) {
        mSelectedIndex = state.getInt(EXTRA_ACTION_SELECTED_INDEX, -1);
    }
    mEntryTransitionPerformed = state.getBoolean(EXTRA_ENTRY_TRANSITION_PERFORMED, false);
}

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

@Override
public void onExportVisitRequest(Bundle paramsBundle) {
    mVisitIdToExport = paramsBundle.getLong(ARG_VISIT_TO_EXPORT_ID);
    if (LDebug.ON)
        Log.d(LOG_TAG, "mVisitIdToExport received in 'onExportVisitRequest' = " + mVisitIdToExport);
    // ARG_VISIT_TO_EXPORT_NAME); // currently unused
    // get filename, either default or overridden in Confirm dialog
    mExportFileName = paramsBundle.getString(ARG_VISIT_TO_EXPORT_FILENAME);
    if (LDebug.ON)
        Log.d(LOG_TAG, "mExportFileName received in 'onExportVisitRequest': " + mExportFileName);
    mResolvePlaceholders = paramsBundle.getBoolean(ARG_RESOLVE_PLACEHOLDERS, true);
    mConnectionRequested = true;/*from w ww. j  a v a 2s .  com*/
    buildGoogleApiClient();
    mGoogleApiClient.connect();
    // create new contents resource
    Drive.DriveApi.newDriveContents(getGoogleApiClient()).setResultCallback(driveContentsCallback);
    // file is actually created by a callback, search in this code for:
    // ResultCallback<DriveContentsResult> driveContentsCallback
}

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  av  a  2 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;
}