Example usage for android.support.v4.util LongSparseArray valueAt

List of usage examples for android.support.v4.util LongSparseArray valueAt

Introduction

In this page you can find the example usage for android.support.v4.util LongSparseArray valueAt.

Prototype

public E valueAt(int i) 

Source Link

Usage

From source file:com.wei.c.im.test.msg.client.MsgListHelper.java

private static <T> void addAll(List<T> list, LongSparseArray<T> map) {
    for (int i = 0; i < map.size(); i++) {
        list.add(map.valueAt(i));
    }/*from w w  w.  java  2  s. c  o m*/
}

From source file:de.vanita5.twittnuker.util.TwitterWrapper.java

public static int removeUnreadCounts(final Context context, final int position,
        final LongSparseArray<Set<Long>> counts) {
    if (context == null || position < 0 || counts == null)
        return 0;
    int result = 0;
    for (int i = 0, j = counts.size(); i < j; i++) {
        final long key = counts.keyAt(i);
        final Set<Long> value = counts.valueAt(i);
        final Uri.Builder builder = UnreadCounts.CONTENT_URI.buildUpon();
        builder.appendPath(String.valueOf(position));
        builder.appendPath(String.valueOf(key));
        builder.appendPath(CollectionUtils.toString(value, ',', false));
        result += context.getContentResolver().delete(builder.build(), null, null);
    }//ww  w .  j  a v  a  2 s  . c o  m
    return result;
}

From source file:com.android.exchange.eas.EasSync.java

/**
 * @return Number of messages successfully synced, or a negative response code from
 *         {@link EasOperation} if we encountered any errors.
 *//* w w w.  j  a v a2s . co  m*/
public final int upsync() {
    final List<MessageStateChange> changes = MessageStateChange.getChanges(mContext, getAccountId(),
            getProtocolVersion() < Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE);
    if (changes == null) {
        return 0;
    }
    final LongSparseArray<List<MessageStateChange>> allData = MessageStateChange.convertToChangesMap(changes);
    if (allData == null) {
        return 0;
    }

    final long[][] messageIds = new long[2][changes.size()];
    final int[] counts = new int[2];
    int result = 0;

    for (int i = 0; i < allData.size(); ++i) {
        mMailboxId = allData.keyAt(i);
        mStateChanges = allData.valueAt(i);
        boolean retryMailbox = true;
        // If we've already encountered a fatal error, don't even try to upsync subsequent
        // mailboxes.
        if (result >= 0) {
            final Cursor mailboxCursor = mContext.getContentResolver().query(
                    ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailboxId),
                    Mailbox.ProjectionSyncData.PROJECTION, null, null, null);
            if (mailboxCursor != null) {
                try {
                    if (mailboxCursor.moveToFirst()) {
                        mMailboxServerId = mailboxCursor.getString(Mailbox.ProjectionSyncData.COLUMN_SERVER_ID);
                        mMailboxSyncKey = mailboxCursor.getString(Mailbox.ProjectionSyncData.COLUMN_SYNC_KEY);
                        if (TextUtils.isEmpty(mMailboxSyncKey) || mMailboxSyncKey.equals("0")) {
                            // For some reason we can get here without a valid mailbox sync key
                            // b/10797675
                            // TODO: figure out why and clean this up
                            LogUtils.d(LOG_TAG, "Tried to sync mailbox %d with invalid mailbox sync key",
                                    mMailboxId);
                        } else {
                            result = performOperation();
                            if (result >= 0) {
                                // Our request gave us back a legitimate answer; this is the
                                // only case in which we don't retry this mailbox.
                                retryMailbox = false;
                                if (result == RESULT_OK) {
                                    handleMessageUpdateStatus(mMessageUpdateStatus, messageIds, counts);
                                } else if (result == RESULT_NO_MAILBOX) {
                                    // A retry here is pointless -- the message's mailbox (and
                                    // therefore the message) is gone, so mark as success so
                                    // that these entries get wiped from the change list.
                                    for (final MessageStateChange msc : mStateChanges) {
                                        messageIds[0][counts[0]] = msc.getMessageId();
                                        ++counts[0];
                                    }
                                } else {
                                    LogUtils.wtf(LOG_TAG, "Unrecognized result code: %d", result);
                                }
                            }
                        }
                    }
                } finally {
                    mailboxCursor.close();
                }
            }
        }
        if (retryMailbox) {
            for (final MessageStateChange msc : mStateChanges) {
                messageIds[1][counts[1]] = msc.getMessageId();
                ++counts[1];
            }
        }
    }

    final ContentResolver cr = mContext.getContentResolver();
    MessageStateChange.upsyncSuccessful(cr, messageIds[0], counts[0]);
    MessageStateChange.upsyncRetry(cr, messageIds[1], counts[1]);

    if (result < 0) {
        return result;
    }
    return counts[0];
}

From source file:com.android.messaging.datamodel.action.SyncMessagesAction.java

/**
 * Batch loading MMS sender for the messages in current batch
 */// w  w  w  . ja va 2s. c  o m
private void setMmsSenders(final LongSparseArray<MmsMessage> mmses, final ThreadInfoCache cache) {
    // Store all the MMS messages
    for (int i = 0; i < mmses.size(); i++) {
        final MmsMessage mms = mmses.valueAt(i);

        final boolean isOutgoing = mms.mType != Mms.MESSAGE_BOX_INBOX;
        String senderId = null;
        if (!isOutgoing) {
            // We only need to find out sender phone number for received message
            senderId = getMmsSender(mms, cache);
            if (senderId == null) {
                LogUtil.w(TAG, "SyncMessagesAction: Could not find sender of incoming MMS " + "message "
                        + mms.getUri() + "; using 'unknown sender' instead");
                senderId = ParticipantData.getUnknownSenderDestination();
            }
        }
        mms.setSender(senderId);
    }
}

From source file:com.snda.mymarket.providers.downloads.DownloadNotifier.java

private void updateWithLocked(LongSparseArray<DownloadInfo> downloads) {
    final Resources res = mContext.getResources();
    // Cluster downloads together
    final Map<String, Collection<DownloadInfo>> clustered = new HashMap<String, Collection<DownloadInfo>>();
    for (int index = 0; index < downloads.size(); index++) {
        final String tag = buildNotificationTag(downloads.valueAt(index));
        if (tag != null) {
            Collection<DownloadInfo> arrDownloads = clustered.get(tag);
            if (arrDownloads == null) {
                arrDownloads = new ArrayList<DownloadInfo>();
                clustered.put(tag, arrDownloads);
            }//from  w w  w.  j  ava 2 s  .  c o m
            arrDownloads.add(downloads.valueAt(index));
        }
    }
    // Build notification for each cluster
    for (String tag : clustered.keySet()) {
        final int type = getNotificationTagType(tag);
        final Collection<DownloadInfo> cluster = clustered.get(tag);
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
        // Use time when cluster was first shown to avoid shuffling
        final long firstShown;
        if (mActiveNotifs.containsKey(tag)) {
            firstShown = mActiveNotifs.get(tag);
        } else {
            firstShown = System.currentTimeMillis();
            mActiveNotifs.put(tag, firstShown);
        }
        builder.setWhen(firstShown);
        // Show relevant icon
        if (type == TYPE_ACTIVE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download);
        } else if (type == TYPE_WAITING) {
            builder.setSmallIcon(android.R.drawable.stat_sys_warning);
        } else if (type == TYPE_COMPLETE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
        }
        // Build action intents
        if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
            // build a synthetic uri for intent identification purposes
            final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build();
            final Intent intent = new Intent(Constants.ACTION_LIST, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
            builder.setOngoing(true);
        } else if (type == TYPE_COMPLETE) {
            final DownloadInfo info = cluster.iterator().next();
            final Uri uri = ContentUris.withAppendedId(Downloads.ALL_DOWNLOADS_CONTENT_URI, info.mId);
            builder.setAutoCancel(true);
            final String action;
            if (Downloads.isStatusError(info.mStatus)) {
                action = Constants.ACTION_LIST;
            } else {
                if (info.mDestination != Downloads.DESTINATION_SYSTEMCACHE_PARTITION) {
                    action = Constants.ACTION_OPEN;
                } else {
                    action = Constants.ACTION_LIST;
                }
            }
            final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
            final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class);
            builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
        }
        // Calculate and show progress
        String remainingText = null;
        String percentText = null;
        if (type == TYPE_ACTIVE) {
            long current = 0;
            long total = 0;
            long speed = 0;
            synchronized (mDownloadSpeed) {
                for (DownloadInfo info : cluster) {
                    if (info.mTotalBytes != -1) {
                        current += info.mCurrentBytes;
                        total += info.mTotalBytes;
                        speed += mDownloadSpeed.get(info.mId) == null ? 0 : mDownloadSpeed.get(info.mId);
                    }
                }
            }

            if (total > 0) {
                final int percent = (int) ((current * 100) / total);
                percentText = res.getString(R.string.download_percent, percent);
                if (speed > 0) {
                    final long remainingMillis = (total - current) / speed;
                    remainingText = res.getString(R.string.download_remaining,
                            DateUtils.formatDuration(remainingMillis));
                }
                builder.setProgress(100, percent, false);
            } else {
                builder.setProgress(100, 0, true);
            }
        }
        // Build titles and description
        final Notification notif;
        if (cluster.size() == 1) {
            final DownloadInfo info = cluster.iterator().next();
            builder.setContentTitle(getDownloadTitle(res, info));
            if (type == TYPE_ACTIVE) {
                if (!TextUtils.isEmpty(info.mDescription)) {
                    builder.setContentText(info.mDescription);
                } else {
                    builder.setContentText(remainingText);
                }
                builder.setContentInfo(percentText);
            } else if (type == TYPE_WAITING) {
                builder.setContentText(res.getString(R.string.notification_need_wifi_for_size));
            } else if (type == TYPE_COMPLETE) {
                if (Downloads.isStatusError(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_failed));
                } else if (Downloads.isStatusSuccess(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_complete));
                }
            }
            notif = builder.build();
        } else {
            final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);
            for (DownloadInfo info : cluster) {
                inboxStyle.addLine(getDownloadTitle(res, info));
            }
            if (type == TYPE_ACTIVE) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_active, cluster.size(), cluster.size()));
                builder.setContentText(remainingText);
                builder.setContentInfo(percentText);
                inboxStyle.setSummaryText(remainingText);
            } else if (type == TYPE_WAITING) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
                builder.setContentText(res.getString(R.string.notification_need_wifi_for_size));
                inboxStyle.setSummaryText(res.getString(R.string.notification_need_wifi_for_size));
            }
            notif = inboxStyle.build();
        }
        mNotifManager.notify(tag, 0, notif);
    }
    // Remove stale tags that weren't renewed
    final Iterator<String> it = mActiveNotifs.keySet().iterator();
    while (it.hasNext()) {
        final String tag = it.next();
        if (!clustered.containsKey(tag)) {
            mNotifManager.cancel(tag, 0);
            it.remove();
        }
    }
}

From source file:org.thialfihar.android.apg.provider.ProviderHelper.java

public PGPKeyRing getPGPKeyRing(Uri queryUri) throws NotFoundException {
    LongSparseArray<PGPKeyRing> result = getPGPKeyRings(queryUri);
    if (result.size() == 0) {
        throw new NotFoundException("PGPKeyRing object not found!");
    } else {/*w w  w .j  av  a 2  s .c  om*/
        return result.valueAt(0);
    }
}

From source file:org.mariotaku.twidere.util.DataStoreUtils.java

@WorkerThread
public static void updateActivity(ContentResolver cr, Uri uri, String where, String[] whereArgs,
        UpdateActivityAction action) {/* w  w w  . j ava2s. c  o  m*/
    final Cursor c = cr.query(uri, Activities.COLUMNS, where, whereArgs, null);
    if (c == null)
        return;
    LongSparseArray<ContentValues> values = new LongSparseArray<>();
    try {
        ParcelableActivityCursorIndices ci = new ParcelableActivityCursorIndices(c);
        c.moveToFirst();
        while (!c.isAfterLast()) {
            final ParcelableActivity activity = ci.newObject(c);
            action.process(activity);
            values.put(activity._id, ParcelableActivityValuesCreator.create(activity));
            c.moveToNext();
        }
    } finally {
        c.close();
    }
    String updateWhere = Expression.equalsArgs(Activities._ID).getSQL();
    String[] updateWhereArgs = new String[1];
    for (int i = 0, j = values.size(); i < j; i++) {
        updateWhereArgs[0] = String.valueOf(values.keyAt(i));
        cr.update(uri, values.valueAt(i), updateWhere, updateWhereArgs);
    }
}

From source file:com.facebook.litho.MountState.java

private static void recordMountedItemsWithTransitionKeys(DataFlowTransitionManager transitionManager,
        LongSparseArray<MountItem> indexToItemMap, boolean isPreMount) {
    for (int i = 0, size = indexToItemMap.size(); i < size; i++) {
        final MountItem item = indexToItemMap.valueAt(i);
        final ViewNodeInfo viewNodeInfo = item.getViewNodeInfo();
        final String transitionKey = viewNodeInfo != null ? viewNodeInfo.getTransitionKey() : null;

        if (transitionKey != null) {
            if (isPreMount) {
                transitionManager.onPreMountItem(transitionKey, (View) item.getContent());
            } else {
                transitionManager.onPostMountItem(transitionKey, (View) item.getContent());
            }//ww w  .  j  a  v  a 2s.c  om
        }
    }
}

From source file:org.sufficientlysecure.keychain.ui.adapter.MultiUserIdsAdapter.java

public ArrayList<CertifyAction> getSelectedCertifyActions() {
    LongSparseArray<CertifyAction> actions = new LongSparseArray<>();
    for (int i = 0; i < mCheckStates.size(); i++) {
        if (mCheckStates.get(i)) {
            mCursor.moveToPosition(i);/*from www  .java 2  s. c  om*/

            long keyId = mCursor.getLong(0);
            byte[] data = mCursor.getBlob(1);

            Parcel p = Parcel.obtain();
            p.unmarshall(data, 0, data.length);
            p.setDataPosition(0);
            ArrayList<String> uids = p.createStringArrayList();
            p.recycle();

            CertifyAction action = actions.get(keyId);
            if (actions.get(keyId) == null) {
                actions.put(keyId, new CertifyAction(keyId, uids, null));
            } else {
                action.mUserIds.addAll(uids);
            }
        }
    }

    ArrayList<CertifyAction> result = new ArrayList<>(actions.size());
    for (int i = 0; i < actions.size(); i++) {
        result.add(actions.valueAt(i));
    }
    return result;
}

From source file:com.android.messaging.datamodel.action.SyncMessagesAction.java

/**
 * Batch loading MMS parts for the messages in current batch
 */// ww  w  .  j a  v a  2 s.c o m
private void loadMmsParts(final LongSparseArray<MmsMessage> mmses) {
    final Context context = Factory.get().getApplicationContext();
    final int totalIds = mmses.size();
    for (int start = 0; start < totalIds; start += MmsUtils.MAX_IDS_PER_QUERY) {
        final int end = Math.min(start + MmsUtils.MAX_IDS_PER_QUERY, totalIds); //excluding
        final int count = end - start;
        final String batchSelection = String.format(Locale.US, "%s != '%s' AND %s IN %s", Mms.Part.CONTENT_TYPE,
                ContentType.APP_SMIL, Mms.Part.MSG_ID, MmsUtils.getSqlInOperand(count));
        final String[] batchSelectionArgs = new String[count];
        for (int i = 0; i < count; i++) {
            batchSelectionArgs[i] = Long.toString(mmses.valueAt(start + i).getId());
        }
        final Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
                MmsUtils.MMS_PART_CONTENT_URI, DatabaseMessages.MmsPart.PROJECTION, batchSelection,
                batchSelectionArgs, null/*sortOrder*/);
        if (cursor != null) {
            try {
                while (cursor.moveToNext()) {
                    // Delay loading the media content for parsing for efficiency
                    // TODO: load the media and fill in the dimensions when
                    // we actually display it
                    final DatabaseMessages.MmsPart part = DatabaseMessages.MmsPart.get(cursor,
                            false/*loadMedia*/);
                    final DatabaseMessages.MmsMessage mms = mmses.get(part.mMessageId);
                    if (mms != null) {
                        mms.addPart(part);
                    }
                }
            } finally {
                cursor.close();
            }
        }
    }
}