Example usage for android.util SparseArray put

List of usage examples for android.util SparseArray put

Introduction

In this page you can find the example usage for android.util SparseArray put.

Prototype

public void put(int key, E value) 

Source Link

Document

Adds a mapping from the specified key to the specified value, replacing the previous mapping from the specified key if there was one.

Usage

From source file:ru.gkpromtech.exhibition.organizations.OrganizationsPagerFragment.java

private void fillItems(int maxItemsPerView) {
    DbHelper db = DbHelper.getInstance(getActivity());

    mItems = new ArrayList<>();
    Table<Organization> organizationsTable = db.getTableFor(Organization.class);
    try {/* www . j  a  v  a 2 s .c  om*/
        List<Pair<Entity[], Organization>> placesOrganizations;

        if (mType == GROUPED) {
            placesOrganizations = organizationsTable.selectJoined(
                    new Table.Join[] { new Table.Join("id", PlacesOrganization.class, "organizationid"),
                            new Table.Join(Place.class, "f1.id = f0.placeid"),
                            new Table.Join(Group.class, "f2.id = f1.groupid") },
                    null, null, "f2.sortorder, t.fullname");
        } else {
            placesOrganizations = organizationsTable.selectJoined(
                    new Table.Join[] { new Table.Join("id", PlacesOrganization.class, "organizationid", "LEFT"),
                            new Table.Join(Place.class, "f1.id = f0.placeid", "LEFT"),
                            new Table.Join(Group.class, "f2.id = f1.groupid", "LEFT") },
                    null, null, "t.fullname");
        }

        String lastTitle = null;
        int pos = 0;
        SparseArray<OrganizationsFragment.Item> itemsCache = new SparseArray<>();
        for (Pair<Entity[], Organization> res : placesOrganizations) {
            Place place = (Place) res.first[1];
            Organization organization = res.second;
            Group group = (Group) res.first[2];

            OrganizationsFragment.Item item = null;
            if (mType == GROUPED) {
                if (!group.name.equals(lastTitle)) {
                    if (mGroupId != null && mGroupPosition == -1 && mGroupId.equals(group.position))
                        mGroupPosition = pos;
                    if (!mSingle || mItems.isEmpty())
                        mItems.add(new ArrayList<OrganizationsFragment.Item>());
                    mItems.get(mItems.size() - 1).add(new OrganizationsFragment.Item(group.name));
                    ++pos;
                    lastTitle = group.name;
                }
            } else {
                if (mItems.isEmpty() || (!mSingle && pos == maxItemsPerView)) {
                    mItems.add(new ArrayList<OrganizationsFragment.Item>());
                    pos = 0;
                }
                item = itemsCache.get(organization.id);
            }

            if (item == null) {
                item = new OrganizationsFragment.Item(group, place, organization);
                item.placesStr = place.name;
                mItems.get(mItems.size() - 1).add(item);
                itemsCache.put(organization.id, item);
            } else {
                if (item.addPlaces == null)
                    item.addPlaces = new ArrayList<>();
                item.addPlaces.add(place);
                item.placesStr += ", " + place.name;
            }
            ++pos;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.actionbarsherlock.internal.view.menu.MenuBuilder.java

private void dispatchSaveInstanceState(Bundle outState) {
    if (mPresenters.isEmpty())
        return;//  w  w  w  . j a  v  a2  s .c  o m

    SparseArray<Parcelable> presenterStates = new SparseArray<Parcelable>();

    for (WeakReference<MenuPresenter> ref : mPresenters) {
        final MenuPresenter presenter = ref.get();
        if (presenter == null) {
            mPresenters.remove(ref);
        } else {
            final int id = presenter.getId();
            if (id > 0) {
                final Parcelable state = presenter.onSaveInstanceState();
                if (state != null) {
                    presenterStates.put(id, state);
                }
            }
        }
    }

    outState.putSparseParcelableArray(PRESENTER_KEY, presenterStates);
}

From source file:android.support.transition.Transition.java

/**
 * This method, essentially a wrapper around all calls to createAnimator for all
 * possible target views, is called with the entire set of start/end
 * values. The implementation in Transition iterates through these lists
 * and calls {@link #createAnimator(android.view.ViewGroup, android.support.transition.TransitionValues, android.support.transition.TransitionValues)}
 * with each set of start/end values on this transition. The
 * TransitionSet subclass overrides this method and delegates it to
 * each of its children in succession./*ww  w .j a  v a 2  s  . com*/
 *
 * @hide
 */
protected void createAnimators(ViewGroup sceneRoot, TransitionValuesMaps startValues,
        TransitionValuesMaps endValues) {
    if (DBG) {
        Log.d(LOG_TAG, "createAnimators() for " + this);
    }
    ArrayMap<View, TransitionValues> endCopy = new ArrayMap<View, TransitionValues>(endValues.viewValues);
    SparseArray<TransitionValues> endIdCopy = new SparseArray<TransitionValues>(endValues.idValues.size());
    for (int i = 0; i < endValues.idValues.size(); ++i) {
        int id = endValues.idValues.keyAt(i);
        endIdCopy.put(id, endValues.idValues.valueAt(i));
    }
    LongSparseArray<TransitionValues> endItemIdCopy = new LongSparseArray<TransitionValues>(
            endValues.itemIdValues.size());
    for (int i = 0; i < endValues.itemIdValues.size(); ++i) {
        long id = endValues.itemIdValues.keyAt(i);
        endItemIdCopy.put(id, endValues.itemIdValues.valueAt(i));
    }
    // Walk through the start values, playing everything we find
    // Remove from the end set as we go
    ArrayList<TransitionValues> startValuesList = new ArrayList<TransitionValues>();
    ArrayList<TransitionValues> endValuesList = new ArrayList<TransitionValues>();
    for (View view : startValues.viewValues.keySet()) {
        TransitionValues start = null;
        TransitionValues end = null;
        boolean isInListView = false;
        if (view.getParent() instanceof ListView) {
            isInListView = true;
        }
        if (!isInListView) {
            int id = view.getId();
            start = startValues.viewValues.get(view) != null ? startValues.viewValues.get(view)
                    : startValues.idValues.get(id);
            if (endValues.viewValues.get(view) != null) {
                end = endValues.viewValues.get(view);
                endCopy.remove(view);
            } else if (id != View.NO_ID) {
                end = endValues.idValues.get(id);
                View removeView = null;
                for (View viewToRemove : endCopy.keySet()) {
                    if (viewToRemove.getId() == id) {
                        removeView = viewToRemove;
                    }
                }
                if (removeView != null) {
                    endCopy.remove(removeView);
                }
            }
            endIdCopy.remove(id);
            if (isValidTarget(view, id)) {
                startValuesList.add(start);
                endValuesList.add(end);
            }
        } else {
            ListView parent = (ListView) view.getParent();
            if (parent.getAdapter().hasStableIds()) {
                int position = parent.getPositionForView(view);
                long itemId = parent.getItemIdAtPosition(position);
                start = startValues.itemIdValues.get(itemId);
                endItemIdCopy.remove(itemId);
                // TODO: deal with targetIDs for itemIDs for ListView items
                startValuesList.add(start);
                endValuesList.add(end);
            }
        }
    }
    int startItemIdCopySize = startValues.itemIdValues.size();
    for (int i = 0; i < startItemIdCopySize; ++i) {
        long id = startValues.itemIdValues.keyAt(i);
        if (isValidTarget(null, id)) {
            TransitionValues start = startValues.itemIdValues.get(id);
            TransitionValues end = endValues.itemIdValues.get(id);
            endItemIdCopy.remove(id);
            startValuesList.add(start);
            endValuesList.add(end);
        }
    }
    // Now walk through the remains of the end set
    for (View view : endCopy.keySet()) {
        int id = view.getId();
        if (isValidTarget(view, id)) {
            TransitionValues start = startValues.viewValues.get(view) != null ? startValues.viewValues.get(view)
                    : startValues.idValues.get(id);
            TransitionValues end = endCopy.get(view);
            endIdCopy.remove(id);
            startValuesList.add(start);
            endValuesList.add(end);
        }
    }
    int endIdCopySize = endIdCopy.size();
    for (int i = 0; i < endIdCopySize; ++i) {
        int id = endIdCopy.keyAt(i);
        if (isValidTarget(null, id)) {
            TransitionValues start = startValues.idValues.get(id);
            TransitionValues end = endIdCopy.get(id);
            startValuesList.add(start);
            endValuesList.add(end);
        }
    }
    int endItemIdCopySize = endItemIdCopy.size();
    for (int i = 0; i < endItemIdCopySize; ++i) {
        long id = endItemIdCopy.keyAt(i);
        // TODO: Deal with targetIDs and itemIDs
        TransitionValues start = startValues.itemIdValues.get(id);
        TransitionValues end = endItemIdCopy.get(id);
        startValuesList.add(start);
        endValuesList.add(end);
    }
    ArrayMap<Animator, AnimationInfo> runningAnimators = getRunningAnimators();
    for (int i = 0; i < startValuesList.size(); ++i) {
        TransitionValues start = startValuesList.get(i);
        TransitionValues end = endValuesList.get(i);
        // Only bother trying to animate with values that differ between start/end
        if (start != null || end != null) {
            if (start == null || !start.equals(end)) {
                if (DBG) {
                    View view = (end != null) ? end.view : start.view;
                    Log.d(LOG_TAG, "  differing start/end values for view " + view);
                    if (start == null || end == null) {
                        Log.d(LOG_TAG, "    "
                                + ((start == null) ? "start null, end non-null" : "start non-null, end null"));
                    } else {
                        for (String key : start.values.keySet()) {
                            Object startValue = start.values.get(key);
                            Object endValue = end.values.get(key);
                            if (startValue != endValue && !startValue.equals(endValue)) {
                                Log.d(LOG_TAG,
                                        "    " + key + ": start(" + startValue + "), end(" + endValue + ")");
                            }
                        }
                    }
                }
                // TODO: what to do about targetIds and itemIds?
                Animator animator = createAnimator(sceneRoot, start, end);
                if (animator != null) {
                    // Save animation info for future cancellation purposes
                    View view = null;
                    TransitionValues infoValues = null;
                    if (end != null) {
                        view = end.view;
                        String[] properties = getTransitionProperties();
                        if (view != null && properties != null && properties.length > 0) {
                            infoValues = new TransitionValues();
                            infoValues.view = view;
                            TransitionValues newValues = endValues.viewValues.get(view);
                            if (newValues != null) {
                                for (int j = 0; j < properties.length; ++j) {
                                    infoValues.values.put(properties[j], newValues.values.get(properties[j]));
                                }
                            }
                            int numExistingAnims = runningAnimators.size();
                            for (int j = 0; j < numExistingAnims; ++j) {
                                Animator anim = runningAnimators.keyAt(j);
                                AnimationInfo info = runningAnimators.get(anim);
                                if (info.values != null && info.view == view
                                        && ((info.name == null && getName() == null)
                                                || info.name.equals(getName()))) {
                                    if (info.values.equals(infoValues)) {
                                        // Favor the old animator
                                        animator = null;
                                        break;
                                    }
                                }
                            }
                        }
                    } else {
                        view = (start != null) ? start.view : null;
                    }
                    if (animator != null) {
                        AnimationInfo info = new AnimationInfo(view, getName(), infoValues);
                        runningAnimators.put(animator, info);
                        mAnimators.add(animator);
                    }
                }
            }
        }
    }
}

From source file:com.fabernovel.alertevoirie.NewsActivity.java

@Override
public void onRequestcompleted(int requestCode, Object result) {
    Log.d(Constants.PROJECT_TAG, "resp : " + result);

    //@formatter:off
    /**/*from  ww w. j  a  va 2s .c om*/
                    
    */
    //@formatter:on 

    try {
        JSONArray responses;
        responses = new JSONArray((String) result);
        response = responses.getJSONObject(0);
        SparseArray<JSONObject> events = new SparseArray<JSONObject>();

        if (requestCode == AVService.REQUEST_JSON) {

            if (JsonData.VALUE_REQUEST_GET_USERS_ACTVITIES.equals(response.getString(JsonData.PARAM_REQUEST))) {
                lock = new Vector<Integer>();
                logs = new SparseArray<JSONObject>();
                logList = new TreeMap<String, JSONObject>(Collections.reverseOrder());
                JSONArray incidentLog = response.getJSONObject(JsonData.PARAM_ANSWER)
                        .getJSONArray(JsonData.PARAM_INCIDENT_LOG);
                for (int i = 0; i < incidentLog.length(); i++) {
                    JSONObject job = incidentLog.getJSONObject(i);
                    logs.put(job.getInt(JsonData.ANSWER_INCIDENT_ID), job);
                    logList.put(job.getString(JsonData.PARAM_INCIDENT_DATE)
                            + job.getLong(JsonData.ANSWER_INCIDENT_ID), job);
                }

                JSONArray items = new JSONArray();

                JSONArray ongoingIncidents = response.getJSONObject(JsonData.PARAM_ANSWER)
                        .getJSONObject(JsonData.PARAM_INCIDENTS).getJSONArray(JsonData.PARAM_ONGOING_INCIDENTS);
                for (int i = 0; i < ongoingIncidents.length(); i++) {
                    JSONObject job = ongoingIncidents.getJSONObject(i);
                    int key = job.getInt(JsonData.PARAM_INCIDENT_ID);
                    if (logs.get(key) != null) {
                        Log.d("AlerteVoirie_PM", "add ongoing incident " + key);
                        events.put(key, job);// items.put(job);
                    }
                }

                JSONArray updatedIncidents = response.getJSONObject(JsonData.PARAM_ANSWER)
                        .getJSONObject(JsonData.PARAM_INCIDENTS).getJSONArray(JsonData.PARAM_UPDATED_INCIDENTS);
                for (int i = 0; i < updatedIncidents.length(); i++) {
                    JSONObject job = updatedIncidents.getJSONObject(i);
                    int key = job.getInt(JsonData.PARAM_INCIDENT_ID);
                    if (logs.get(key) != null) {
                        Log.d("AlerteVoirie_PM", "add updated incident " + key);
                        events.put(key, job);
                    }
                }

                JSONArray resolvedIncidents = response.getJSONObject(JsonData.PARAM_ANSWER)
                        .getJSONObject(JsonData.PARAM_INCIDENTS)
                        .getJSONArray(JsonData.PARAM_RESOLVED_INCIDENTS);
                for (int i = 0; i < resolvedIncidents.length(); i++) {
                    JSONObject job = resolvedIncidents.getJSONObject(i);
                    int key = job.getInt(JsonData.PARAM_INCIDENT_ID);
                    if (logs.get(key) != null) {
                        Log.d("AlerteVoirie_PM", "add resolved incident " + key);
                        events.put(key, job);
                    }
                }

                for (JSONObject log : logList.values()) {
                    int id = log.getInt(JsonData.ANSWER_INCIDENT_ID);
                    Log.d("AlerteVoirie_PM", "key bug " + id);
                    JSONObject jsonObject = events.get(id);
                    if (jsonObject != null) {
                        String json = jsonObject.toString();
                        JSONObject job = new JSONObject(json);
                        job.put(JsonData.PARAM_INCIDENT_DATE, log.getString(JsonData.PARAM_INCIDENT_DATE));
                        items.put(job);

                        if (JsonData.PARAM_UPDATE_INCIDENT_INVALID.equals(log.getString(JsonData.PARAM_STATUS))
                                || JsonData.PARAM_UPDATE_INCIDENT_RESOLVED
                                        .equals(log.getString(JsonData.PARAM_STATUS))) {
                            lock.add(id);
                        }
                    }
                }

                setListAdapter(new MagicAdapter(this, items, R.layout.cell_report,
                        new String[] { JsonData.PARAM_INCIDENT_DESCRIPTION, JsonData.PARAM_INCIDENT_ADDRESS },
                        new int[] { R.id.TextView_title, R.id.TextView_text }, null));
            }

        }

    } catch (JSONException e) {
        Log.e(Constants.PROJECT_TAG, "error in onRequestcompleted : ", e);
    } catch (ClassCastException e) {
        Log.e(Constants.PROJECT_TAG, "error in onRequestcompleted : CLasscastException", e);
    } catch (NullPointerException e) {
        Log.e(Constants.PROJECT_TAG, "error in onRequestcompleted : NullPointerException", e);
    } finally {

        if (requestCode == AVService.REQUEST_JSON)
            dismissDialog(DIALOG_PROGRESS);
    }

}

From source file:com.gh.bmd.jrt.android.v4.core.LoaderInvocation.java

@Override
@SuppressWarnings("unchecked")
@SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE", justification = "class comparison with == is done")
public void onCall(@Nonnull final List<? extends INPUT> inputs, @Nonnull final ResultChannel<OUTPUT> result) {

    final Logger logger = mLogger;
    final Object context = mContext.get();

    if (context == null) {

        logger.dbg("avoiding running invocation since context is null");
        return;//  www  .  ja v  a2  s. c  o  m
    }

    final Context loaderContext;
    final LoaderManager loaderManager;

    if (context instanceof FragmentActivity) {

        final FragmentActivity activity = (FragmentActivity) context;
        loaderContext = activity.getApplicationContext();
        loaderManager = activity.getSupportLoaderManager();
        logger.dbg("running invocation bound to activity: %s", activity);

    } else if (context instanceof Fragment) {

        final Fragment fragment = (Fragment) context;
        loaderContext = fragment.getActivity().getApplicationContext();
        loaderManager = fragment.getLoaderManager();
        logger.dbg("running invocation bound to fragment: %s", fragment);

    } else {

        throw new IllegalArgumentException("invalid context type: " + context.getClass().getCanonicalName());
    }

    int loaderId = mLoaderId;

    if (loaderId == ContextRoutineBuilder.AUTO) {

        loaderId = mConstructor.getDeclaringClass().hashCode();

        for (final Object arg : mArgs) {

            loaderId = 31 * loaderId + recursiveHashCode(arg);
        }

        loaderId = 31 * loaderId + inputs.hashCode();
        logger.dbg("generating invocation ID: %d", loaderId);
    }

    final Loader<InvocationResult<OUTPUT>> loader = loaderManager.getLoader(loaderId);
    final boolean isClash = isClash(loader, loaderId, inputs);
    final WeakIdentityHashMap<Object, SparseArray<WeakReference<RoutineLoaderCallbacks<?>>>> callbackMap = sCallbackMap;
    SparseArray<WeakReference<RoutineLoaderCallbacks<?>>> callbackArray = callbackMap.get(context);

    if (callbackArray == null) {

        callbackArray = new SparseArray<WeakReference<RoutineLoaderCallbacks<?>>>();
        callbackMap.put(context, callbackArray);
    }

    final WeakReference<RoutineLoaderCallbacks<?>> callbackReference = callbackArray.get(loaderId);
    RoutineLoaderCallbacks<OUTPUT> callbacks = (callbackReference != null)
            ? (RoutineLoaderCallbacks<OUTPUT>) callbackReference.get()
            : null;

    if ((callbacks == null) || (loader == null) || isClash) {

        final RoutineLoader<INPUT, OUTPUT> routineLoader;

        if (!isClash && (loader != null) && (loader.getClass() == RoutineLoader.class)) {

            routineLoader = (RoutineLoader<INPUT, OUTPUT>) loader;

        } else {

            routineLoader = null;
        }

        final RoutineLoaderCallbacks<OUTPUT> newCallbacks = createCallbacks(loaderContext, loaderManager,
                routineLoader, inputs, loaderId);

        if (callbacks != null) {

            logger.dbg("resetting existing callbacks [%d]", loaderId);
            callbacks.reset();
        }

        callbackArray.put(loaderId, new WeakReference<RoutineLoaderCallbacks<?>>(newCallbacks));
        callbacks = newCallbacks;
    }

    logger.dbg("setting result cache type [%d]: %s", loaderId, mCacheStrategyType);
    callbacks.setCacheStrategy(mCacheStrategyType);

    final OutputChannel<OUTPUT> outputChannel = callbacks.newChannel();

    if (isClash) {

        logger.dbg("restarting loader [%d]", loaderId);
        loaderManager.restartLoader(loaderId, Bundle.EMPTY, callbacks);

    } else {

        logger.dbg("initializing loader [%d]", loaderId);
        loaderManager.initLoader(loaderId, Bundle.EMPTY, callbacks);
    }

    result.pass(outputChannel);
}

From source file:com.oakesville.mythling.MediaActivity.java

SparseArray<String> getLongClickMenuItems(Item item) {
    String[] menuItems = getResources().getStringArray(R.array.item_long_click_menu);
    SparseArray<String> relevantItems = new SparseArray<String>();
    for (int i = 0; i < menuItems.length; i++) {
        if (i == LONG_CLICK_MENU_PLAY)
            relevantItems.put(i, menuItems[i]);
        else if (i == LONG_CLICK_MENU_TRANSCODE && !item.isMusic())
            relevantItems.put(i, menuItems[i]);
        else if (i == LONG_CLICK_MENU_DOWNLOAD && !item.isLiveTv())
            relevantItems.put(i, menuItems[i]);
        else if (i == LONG_CLICK_MENU_DELETE && item.isRecording())
            relevantItems.put(i, menuItems[i]);
    }//from  www .j a va  2  s  .c  o m
    return relevantItems;
}

From source file:com.android.messaging.mmslib.pdu.PduPersister.java

/**
 * Persist a PDU object to specific location in the storage.
 *
 * @param pdu             The PDU object to be stored.
 * @param uri             Where to store the given PDU object.
 * @param subId           Subscription id associated with this message.
 * @param subPhoneNumber TODO/*w  w w  .ja  va2 s  . c o m*/
 * @param preOpenedFiles  if not null, a map of preopened InputStreams for the parts.
 * @return A Uri which can be used to access the stored PDU.
 */
public Uri persist(final GenericPdu pdu, final Uri uri, final int subId, final String subPhoneNumber,
        final Map<Uri, InputStream> preOpenedFiles) throws MmsException {
    if (uri == null) {
        throw new MmsException("Uri may not be null.");
    }
    long msgId = -1;
    try {
        msgId = ContentUris.parseId(uri);
    } catch (final NumberFormatException e) {
        // the uri ends with "inbox" or something else like that
    }
    final boolean existingUri = msgId != -1;

    if (!existingUri && MESSAGE_BOX_MAP.get(uri) == null) {
        throw new MmsException("Bad destination, must be one of " + "content://mms/inbox, content://mms/sent, "
                + "content://mms/drafts, content://mms/outbox, " + "content://mms/temp.");
    }
    synchronized (PDU_CACHE_INSTANCE) {
        // If the cache item is getting updated, wait until it's done updating before
        // purging it.
        if (PDU_CACHE_INSTANCE.isUpdating(uri)) {
            if (LOCAL_LOGV) {
                LogUtil.v(TAG, "persist: " + uri + " blocked by isUpdating()");
            }
            try {
                PDU_CACHE_INSTANCE.wait();
            } catch (final InterruptedException e) {
                Log.e(TAG, "persist1: ", e);
            }
        }
    }
    PDU_CACHE_INSTANCE.purge(uri);

    final PduHeaders header = pdu.getPduHeaders();
    PduBody body = null;
    ContentValues values = new ContentValues();

    // Mark new messages as seen in the telephony database so that we don't have to
    // do a global "set all messages as seen" since that occasionally seems to be
    // problematic (i.e. very slow).  See bug 18189471.
    values.put(Mms.SEEN, 1);

    //Set<Entry<Integer, String>> set;

    for (int i = ENCODED_STRING_COLUMN_NAME_MAP.size(); --i >= 0;) {
        final int field = ENCODED_STRING_COLUMN_NAME_MAP.keyAt(i);
        final EncodedStringValue encodedString = header.getEncodedStringValue(field);
        if (encodedString != null) {
            final String charsetColumn = CHARSET_COLUMN_NAME_MAP.get(field);
            values.put(ENCODED_STRING_COLUMN_NAME_MAP.valueAt(i), toIsoString(encodedString.getTextString()));
            values.put(charsetColumn, encodedString.getCharacterSet());
        }
    }

    for (int i = TEXT_STRING_COLUMN_NAME_MAP.size(); --i >= 0;) {
        final byte[] text = header.getTextString(TEXT_STRING_COLUMN_NAME_MAP.keyAt(i));
        if (text != null) {
            values.put(TEXT_STRING_COLUMN_NAME_MAP.valueAt(i), toIsoString(text));
        }
    }

    for (int i = OCTET_COLUMN_NAME_MAP.size(); --i >= 0;) {
        final int b = header.getOctet(OCTET_COLUMN_NAME_MAP.keyAt(i));
        if (b != 0) {
            values.put(OCTET_COLUMN_NAME_MAP.valueAt(i), b);
        }
    }

    for (int i = LONG_COLUMN_NAME_MAP.size(); --i >= 0;) {
        final long l = header.getLongInteger(LONG_COLUMN_NAME_MAP.keyAt(i));
        if (l != -1L) {
            values.put(LONG_COLUMN_NAME_MAP.valueAt(i), l);
        }
    }

    final SparseArray<EncodedStringValue[]> addressMap = new SparseArray<EncodedStringValue[]>(
            ADDRESS_FIELDS.length);
    // Save address information.
    for (final int addrType : ADDRESS_FIELDS) {
        EncodedStringValue[] array = null;
        if (addrType == PduHeaders.FROM) {
            final EncodedStringValue v = header.getEncodedStringValue(addrType);
            if (v != null) {
                array = new EncodedStringValue[1];
                array[0] = v;
            }
        } else {
            array = header.getEncodedStringValues(addrType);
        }
        addressMap.put(addrType, array);
    }

    final HashSet<String> recipients = new HashSet<String>();
    final int msgType = pdu.getMessageType();
    // Here we only allocate thread ID for M-Notification.ind,
    // M-Retrieve.conf and M-Send.req.
    // Some of other PDU types may be allocated a thread ID outside
    // this scope.
    if ((msgType == PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND)
            || (msgType == PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF)
            || (msgType == PduHeaders.MESSAGE_TYPE_SEND_REQ)) {
        switch (msgType) {
        case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND:
        case PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF:
            loadRecipients(PduHeaders.FROM, recipients, addressMap);

            // For received messages (whether group MMS is enabled or not) we want to
            // associate this message with the thread composed of all the recipients
            // EXCLUDING our own number. This includes the person who sent the
            // message (the FROM field above) in addition to the other people the message
            // was addressed TO (or CC fields to address group messaging compatibility
            // issues with devices that place numbers in this field). Typically our own
            // number is in the TO/CC field so we have to remove it in loadRecipients.
            checkAndLoadToCcRecipients(recipients, addressMap, subPhoneNumber);
            break;
        case PduHeaders.MESSAGE_TYPE_SEND_REQ:
            loadRecipients(PduHeaders.TO, recipients, addressMap);
            break;
        }
        long threadId = -1L;
        if (!recipients.isEmpty()) {
            // Given all the recipients associated with this message, find (or create) the
            // correct thread.
            threadId = MmsSmsUtils.Threads.getOrCreateThreadId(mContext, recipients);
        } else {
            LogUtil.w(TAG, "PduPersister.persist No recipients; persisting PDU to thread: " + threadId);
        }
        values.put(Mms.THREAD_ID, threadId);
    }

    // Save parts first to avoid inconsistent message is loaded
    // while saving the parts.
    final long dummyId = System.currentTimeMillis(); // Dummy ID of the msg.

    // Figure out if this PDU is a text-only message
    boolean textOnly = true;

    // Get body if the PDU is a RetrieveConf or SendReq.
    if (pdu instanceof MultimediaMessagePdu) {
        body = ((MultimediaMessagePdu) pdu).getBody();
        // Start saving parts if necessary.
        if (body != null) {
            final int partsNum = body.getPartsNum();
            if (LOCAL_LOGV) {
                LogUtil.v(TAG, "PduPersister.persist partsNum: " + partsNum);
            }
            if (partsNum > 2) {
                // For a text-only message there will be two parts: 1-the SMIL, 2-the text.
                // Down a few lines below we're checking to make sure we've only got SMIL or
                // text. We also have to check then we don't have more than two parts.
                // Otherwise, a slideshow with two text slides would be marked as textOnly.
                textOnly = false;
            }
            for (int i = 0; i < partsNum; i++) {
                final PduPart part = body.getPart(i);
                persistPart(part, dummyId, preOpenedFiles);

                // If we've got anything besides text/plain or SMIL part, then we've got
                // an mms message with some other type of attachment.
                final String contentType = getPartContentType(part);
                if (LOCAL_LOGV) {
                    LogUtil.v(TAG, "PduPersister.persist part: " + i + " contentType: " + contentType);
                }
                if (contentType != null && !ContentType.APP_SMIL.equals(contentType)
                        && !ContentType.TEXT_PLAIN.equals(contentType)) {
                    textOnly = false;
                }
            }
        }
    }
    // Record whether this mms message is a simple plain text or not. This is a hint for the
    // UI.
    if (OsUtil.isAtLeastJB_MR1()) {
        values.put(Mms.TEXT_ONLY, textOnly ? 1 : 0);
    }

    if (OsUtil.isAtLeastL_MR1()) {
        values.put(Mms.SUBSCRIPTION_ID, subId);
    } else {
        Assert.equals(ParticipantData.DEFAULT_SELF_SUB_ID, subId);
    }

    Uri res = null;
    if (existingUri) {
        res = uri;
        SqliteWrapper.update(mContext, mContentResolver, res, values, null, null);
    } else {
        res = SqliteWrapper.insert(mContext, mContentResolver, uri, values);
        if (res == null) {
            throw new MmsException("persist() failed: return null.");
        }
        // Get the real ID of the PDU and update all parts which were
        // saved with the dummy ID.
        msgId = ContentUris.parseId(res);
    }

    values = new ContentValues(1);
    values.put(Part.MSG_ID, msgId);
    SqliteWrapper.update(mContext, mContentResolver, Uri.parse("content://mms/" + dummyId + "/part"), values,
            null, null);
    // We should return the longest URI of the persisted PDU, for
    // example, if input URI is "content://mms/inbox" and the _ID of
    // persisted PDU is '8', we should return "content://mms/inbox/8"
    // instead of "content://mms/8".
    // TODO: Should the MmsProvider be responsible for this???
    if (!existingUri) {
        res = Uri.parse(uri + "/" + msgId);
    }

    // Save address information.
    for (final int addrType : ADDRESS_FIELDS) {
        final EncodedStringValue[] array = addressMap.get(addrType);
        if (array != null) {
            persistAddress(msgId, addrType, array);
        }
    }

    return res;
}

From source file:edu.umich.flowfence.sandbox.ResolvedQM.java

@Override
public void call(int flags, IQMCallback callback, List<CallParam> params) throws RemoteException {
    try {/*ww  w  . j ava2 s.co m*/
        if (localLOGD) {
            Log.d(TAG, String.format("Incoming sandbox call for %s, %d parameters:", mOriginalDescriptor,
                    params.size()));
            for (CallParam param : params) {
                Log.d(TAG, param.toString(mContext.getClassLoader()));
            }
        }
        if (localLOGV) {
            Log.v(TAG, String.format("Callback %s, flags %d", callback, flags));
        }
        // Sanity check.
        final int numParams = params.size();
        if (numParams != mMemberData.countParameters()) {
            throw new IllegalArgumentException("Wrong number of arguments supplied");
        }

        boolean hasReturn = (flags & CallFlags.NO_RETURN_VALUE) == 0;

        final ArrayList<Object> args = new ArrayList<>();
        final SparseArray<IBinder> outs = new SparseArray<>();

        mContext.beginQM();
        try {
            if (hasReturn) {
                outs.append(CallResult.RETURN_VALUE, null);
            }

            for (int i = 0; i < numParams; i++) {
                CallParam param = params.get(i);
                int paramHeader = param.getHeader();
                if (param.getType() == CallParam.TYPE_HANDLE
                        && (paramHeader & CallParam.HANDLE_SYNC_ONLY) != 0) {
                    Log.w(TAG, "HANDLE_SYNC_ONLY in sandbox for " + mOriginalDescriptor);
                    continue;
                }
                // Deserialize argument, marshaling as necessary.
                Object arg = unpack(param);
                // TODO: FLAG_BY_REF
                args.add(arg);
                // Put together the out parameter for inout params.
                if ((paramHeader & CallParam.FLAG_RETURN) != 0) {
                    if (localLOGV) {
                        Log.v(TAG, String.format("Adding out param %d", i));
                    }
                    outs.append(i, SandboxObject.binderForObject(this, arg));
                }
            }

            // Actually do the call.
            Object[] argArray = args.toArray();
            if (localLOGD) {
                Log.d(TAG, "Preparing to call " + mOriginalDescriptor.printCall(argArray));
            }

            Object retval = mMemberData.call(argArray);

            if (localLOGD) {
                Log.d(TAG, "Call returned: " + Objects.toString(retval));
            }

            // Bundle up handle for return value.
            if (hasReturn) {
                IBinder retvalObj = SandboxObject.binderForObject(this, retval);
                outs.put(CallResult.RETURN_VALUE, retvalObj);
            }

            // DEBUG: print out params
            if (localLOGV) {
                for (int i = 0; i < outs.size(); i++) {
                    Log.v(TAG, String.format("out[%d] = %s", outs.keyAt(i), outs.valueAt(i)));
                }
            }
            // Post results to caller.
            if (localLOGD) {
                Log.d(TAG, "Posting results to caller");
            }
            callback.onResult(new CallResult(outs));
        } catch (InvocationTargetException ioe) {
            Throwable t = ioe.getTargetException();
            if (t instanceof Exception) {
                throw ((Exception) t);
            }
            throw ioe;
        } finally {
            // Clear our ambient context.
            if (localLOGD) {
                Log.d(TAG, "Clearing call token");
            }
            mContext.endQM();
        }
    } catch (Exception e) {
        //Log.e(TAG, String.format("Error invoking %s", mOriginalDescriptor), e);
        callback.onResult(new CallResult(e));
    }
}

From source file:edu.umich.oasis.sandbox.ResolvedSoda.java

@Override
public void call(int flags, ISodaCallback callback, List<CallParam> params) throws RemoteException {
    try {/* w ww  . j  ava 2  s .c o  m*/
        if (localLOGD) {
            Log.d(TAG, String.format("Incoming sandbox call for %s, %d parameters:", mOriginalDescriptor,
                    params.size()));
            for (CallParam param : params) {
                Log.d(TAG, param.toString(mContext.getClassLoader()));
            }
        }
        if (localLOGV) {
            Log.v(TAG, String.format("Callback %s, flags %d", callback, flags));
        }
        // Sanity check.
        final int numParams = params.size();
        if (numParams != mMemberData.countParameters()) {
            throw new IllegalArgumentException("Wrong number of arguments supplied");
        }

        boolean hasReturn = (flags & CallFlags.NO_RETURN_VALUE) == 0;

        final ArrayList<Object> args = new ArrayList<>();
        final SparseArray<IBinder> outs = new SparseArray<>();

        mContext.beginSoda();
        try {
            if (hasReturn) {
                outs.append(CallResult.RETURN_VALUE, null);
            }

            for (int i = 0; i < numParams; i++) {
                CallParam param = params.get(i);
                int paramHeader = param.getHeader();
                if (param.getType() == CallParam.TYPE_HANDLE
                        && (paramHeader & CallParam.HANDLE_SYNC_ONLY) != 0) {
                    Log.w(TAG, "HANDLE_SYNC_ONLY in sandbox for " + mOriginalDescriptor);
                    continue;
                }
                // Deserialize argument, marshaling as necessary.
                Object arg = unpack(param);
                // TODO: FLAG_BY_REF
                args.add(arg);
                // Put together the out parameter for inout params.
                if ((paramHeader & CallParam.FLAG_RETURN) != 0) {
                    if (localLOGV) {
                        Log.v(TAG, String.format("Adding out param %d", i));
                    }
                    outs.append(i, SandboxObject.binderForObject(this, arg));
                }
            }

            // Actually do the call.
            Object[] argArray = args.toArray();
            if (localLOGD) {
                Log.d(TAG, "Preparing to call " + mOriginalDescriptor.printCall(argArray));
            }

            Object retval = mMemberData.call(argArray);

            if (localLOGD) {
                Log.d(TAG, "Call returned: " + Objects.toString(retval));
            }

            // Bundle up handle for return value.
            if (hasReturn) {
                IBinder retvalObj = SandboxObject.binderForObject(this, retval);
                outs.put(CallResult.RETURN_VALUE, retvalObj);
            }

            // DEBUG: print out params
            if (localLOGV) {
                for (int i = 0; i < outs.size(); i++) {
                    Log.v(TAG, String.format("out[%d] = %s", outs.keyAt(i), outs.valueAt(i)));
                }
            }
            // Post results to caller.
            if (localLOGD) {
                Log.d(TAG, "Posting results to caller");
            }
            callback.onResult(new CallResult(outs));
        } catch (InvocationTargetException ioe) {
            Throwable t = ioe.getTargetException();
            if (t instanceof Exception) {
                throw ((Exception) t);
            }
            throw ioe;
        } finally {
            // Clear our ambient context.
            if (localLOGD) {
                Log.d(TAG, "Clearing call token");
            }
            mContext.endSoda();
        }
    } catch (Exception e) {
        //Log.e(TAG, String.format("Error invoking %s", mOriginalDescriptor), e);
        callback.onResult(new CallResult(e));
    }
}

From source file:com.althink.android.ossw.ble.ScanRecord.java

/**
 * Parse scan record bytes to {@link ScanRecord}.
 * <p>//from  w  ww. j a  va 2  s .  c  om
 * The format is defined in Bluetooth 4.1 specification, Volume 3, Part C, Section 11 and 18.
 * <p>
 * All numerical multi-byte entities and values shall use little-endian <strong>byte</strong>
 * order.
 *
 * @param scanRecord The scan record of Bluetooth LE advertisement and/or scan response.
 * @hide
 */
public static ScanRecord parseFromBytes(byte[] scanRecord) {
    if (scanRecord == null) {
        return null;
    }

    int currentPos = 0;
    int advertiseFlag = -1;
    List<ParcelUuid> serviceUuids = new ArrayList<ParcelUuid>();
    String localName = null;
    int txPowerLevel = Integer.MIN_VALUE;

    SparseArray<byte[]> manufacturerData = new SparseArray<byte[]>();
    Map<ParcelUuid, byte[]> serviceData = new ArrayMap<>();

    try {
        while (currentPos < scanRecord.length) {
            // length is unsigned int.
            int length = scanRecord[currentPos++] & 0xFF;
            if (length == 0) {
                break;
            }
            // Note the length includes the length of the field type itself.
            int dataLength = length - 1;
            // fieldType is unsigned int.
            int fieldType = scanRecord[currentPos++] & 0xFF;
            switch (fieldType) {
            case DATA_TYPE_FLAGS:
                advertiseFlag = scanRecord[currentPos] & 0xFF;
                break;
            case DATA_TYPE_SERVICE_UUIDS_16_BIT_PARTIAL:
            case DATA_TYPE_SERVICE_UUIDS_16_BIT_COMPLETE:
                parseServiceUuid(scanRecord, currentPos, dataLength, BluetoothUuid.UUID_BYTES_16_BIT,
                        serviceUuids);
                break;
            case DATA_TYPE_SERVICE_UUIDS_32_BIT_PARTIAL:
            case DATA_TYPE_SERVICE_UUIDS_32_BIT_COMPLETE:
                parseServiceUuid(scanRecord, currentPos, dataLength, BluetoothUuid.UUID_BYTES_32_BIT,
                        serviceUuids);
                break;
            case DATA_TYPE_SERVICE_UUIDS_128_BIT_PARTIAL:
            case DATA_TYPE_SERVICE_UUIDS_128_BIT_COMPLETE:
                parseServiceUuid(scanRecord, currentPos, dataLength, BluetoothUuid.UUID_BYTES_128_BIT,
                        serviceUuids);
                break;
            case DATA_TYPE_LOCAL_NAME_SHORT:
            case DATA_TYPE_LOCAL_NAME_COMPLETE:
                localName = new String(extractBytes(scanRecord, currentPos, dataLength));
                break;
            case DATA_TYPE_TX_POWER_LEVEL:
                txPowerLevel = scanRecord[currentPos];
                break;
            case DATA_TYPE_SERVICE_DATA:
                // The first two bytes of the service data are service data UUID in little
                // endian. The rest bytes are service data.
                int serviceUuidLength = BluetoothUuid.UUID_BYTES_16_BIT;
                byte[] serviceDataUuidBytes = extractBytes(scanRecord, currentPos, serviceUuidLength);
                ParcelUuid serviceDataUuid = BluetoothUuid.parseUuidFrom(serviceDataUuidBytes);
                byte[] serviceDataArray = extractBytes(scanRecord, currentPos + serviceUuidLength,
                        dataLength - serviceUuidLength);
                serviceData.put(serviceDataUuid, serviceDataArray);
                break;
            case DATA_TYPE_MANUFACTURER_SPECIFIC_DATA:
                // The first two bytes of the manufacturer specific data are
                // manufacturer ids in little endian.
                int manufacturerId = ((scanRecord[currentPos + 1] & 0xFF) << 8)
                        + (scanRecord[currentPos] & 0xFF);
                byte[] manufacturerDataBytes = extractBytes(scanRecord, currentPos + 2, dataLength - 2);
                manufacturerData.put(manufacturerId, manufacturerDataBytes);
                break;
            default:
                // Just ignore, we don't handle such data type.
                break;
            }
            currentPos += dataLength;
        }

        if (serviceUuids.isEmpty()) {
            serviceUuids = null;
        }
        return new ScanRecord(serviceUuids, manufacturerData, serviceData, advertiseFlag, txPowerLevel,
                localName, scanRecord);
    } catch (Exception e) {
        //Log.e(TAG, "unable to parse scan record: " + Arrays.toString(scanRecord));
        // As the record is invalid, ignore all the parsed results for this packet
        // and return an empty record with raw scanRecord bytes in results
        return new ScanRecord(null, null, null, -1, Integer.MIN_VALUE, null, scanRecord);
    }
}