Example usage for android.util SparseArray SparseArray

List of usage examples for android.util SparseArray SparseArray

Introduction

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

Prototype

public SparseArray() 

Source Link

Document

Creates a new SparseArray containing no mappings.

Usage

From source file:android.support.v7.widget.AppCompatDrawableManager.java

private Drawable loadDrawableFromDelegates(@NonNull Context context, @DrawableRes int resId) {
    if (mDelegates != null && !mDelegates.isEmpty()) {
        if (mKnownDrawableIdTags != null) {
            final String cachedTagName = mKnownDrawableIdTags.get(resId);
            if (SKIP_DRAWABLE_TAG.equals(cachedTagName)
                    || (cachedTagName != null && mDelegates.get(cachedTagName) == null)) {
                // If we don't have a delegate for the drawable tag, or we've been set to
                // skip it, fail fast and return null
                if (DEBUG) {
                    Log.d(TAG, "[loadDrawableFromDelegates] Skipping drawable: "
                            + context.getResources().getResourceName(resId));
                }//from  w  w  w  .j a  va 2  s .  com
                return null;
            }
        } else {
            // Create an id cache as we'll need one later
            mKnownDrawableIdTags = new SparseArray<>();
        }

        if (mTypedValue == null) {
            mTypedValue = new TypedValue();
        }
        final TypedValue tv = mTypedValue;
        final Resources res = context.getResources();
        res.getValue(resId, tv, true);

        final long key = createCacheKey(tv);

        Drawable dr = getCachedDrawable(context, key);
        if (dr != null) {
            if (DEBUG) {
                Log.i(TAG, "[loadDrawableFromDelegates] Returning cached drawable: "
                        + context.getResources().getResourceName(resId));
            }
            // We have a cached drawable, return it!
            return dr;
        }

        if (tv.string != null && tv.string.toString().endsWith(".xml")) {
            // If the resource is an XML file, let's try and parse it
            try {
                final XmlPullParser parser = res.getXml(resId);
                final AttributeSet attrs = Xml.asAttributeSet(parser);
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG
                        && type != XmlPullParser.END_DOCUMENT) {
                    // Empty loop
                }
                if (type != XmlPullParser.START_TAG) {
                    throw new XmlPullParserException("No start tag found");
                }

                final String tagName = parser.getName();
                // Add the tag name to the cache
                mKnownDrawableIdTags.append(resId, tagName);

                // Now try and find a delegate for the tag name and inflate if found
                final InflateDelegate delegate = mDelegates.get(tagName);
                if (delegate != null) {
                    dr = delegate.createFromXmlInner(context, parser, attrs, context.getTheme());
                }
                if (dr != null) {
                    // Add it to the drawable cache
                    dr.setChangingConfigurations(tv.changingConfigurations);
                    if (addDrawableToCache(context, key, dr) && DEBUG) {
                        Log.i(TAG, "[loadDrawableFromDelegates] Saved drawable to cache: "
                                + context.getResources().getResourceName(resId));
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "Exception while inflating drawable", e);
            }
        }
        if (dr == null) {
            // If we reach here then the delegate inflation of the resource failed. Mark it as
            // bad so we skip the id next time
            mKnownDrawableIdTags.append(resId, SKIP_DRAWABLE_TAG);
        }
        return dr;
    }

    return null;
}

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

@Override
public void call(int flags, ISodaCallback callback, List<CallParam> params) throws RemoteException {
    try {/*from ww w .j ava 2  s .com*/
        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:edu.umich.flowfence.sandbox.ResolvedQM.java

@Override
public void call(int flags, IQMCallback callback, List<CallParam> params) throws RemoteException {
    try {/*w w  w .  j av  a2  s .  c  om*/
        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:org.ale.scanner.zotero.MainActivity.java

public void loadGroups() {
    if (mAccountAccess.getGroupCount() == 0 && mAccountAccess.canWriteLibrary()) {
        mGroups = new SparseArray<PString>();
        mGroups.put(Group.GROUP_LIBRARY, new PString(getString(R.string.my_library)));
        return;/*from   ww w  .  j  av a2  s.  c  om*/
    }
    // Check that we have all the group titles
    new Thread(new Runnable() {
        public void run() {
            final SparseArray<PString> newGroupList = new SparseArray<PString>();
            Set<Integer> groups = mAccountAccess.getGroupIds();
            if (mAccountAccess.canWriteLibrary()) {
                newGroupList.put(Group.GROUP_LIBRARY, new PString(getString(R.string.my_library)));
            }
            String[] selection = new String[] { TextUtils.join(",", groups) };
            Cursor c = getContentResolver().query(Database.GROUP_URI,
                    new String[] { Group._ID, Group.COL_TITLE }, Group._ID + " IN (?)", selection, null);

            // Figure out which groups we don't have
            c.moveToFirst();
            while (!c.isAfterLast()) {
                int haveGroupId = c.getInt(0);
                groups.remove(haveGroupId);
                newGroupList.put(haveGroupId, new PString(c.getString(1)));
                c.moveToNext();
            }
            c.close();
            // Update the group list
            mUIThreadHandler.post(new Runnable() {
                public void run() {
                    mGroups = newGroupList;
                }
            });
            // If we have any unknown groups, do a group lookup.
            if (groups.size() > 0) {
                // Make new database entries for new groups. Mapping each
                // id to "<Group ID>" temporarily.
                ContentValues[] values = new ContentValues[groups.size()];
                int i = 0;
                for (Integer gid : groups) {
                    values[i] = new ContentValues();
                    values[i].put(Group._ID, gid);
                    values[i].put(Group.COL_TITLE, "<" + gid + ">");
                    i++;
                }
                getContentResolver().bulkInsert(Database.GROUP_URI, values);
                mZAPI.getGroups();
            }
        }
    }).start();
}

From source file:pl.motyczko.scrollheader.PagerSlidingTabStrip.java

public void notifyDataSetChanged() {
    tabsContainer.removeAllViews();/* w  w  w.  ja  va  2  s  . c  o  m*/
    mCoordinates = new SparseArray<Coordinate>();
    int pageCount = pager.getAdapter().getCount();
    tabCount = pager.getAdapter().getCount();

    for (int i = 0; i < tabCount; i++) {

        if (pager.getAdapter() instanceof IconTabProvider) {
            addIconTab(i, ((IconTabProvider) pager.getAdapter()).getPageIconResId(i));
        } else {
            addTextTab(i, pager.getAdapter().getPageTitle(i).toString());
        }

    }

    updateTabStyles();

    getViewTreeObserver().addOnGlobalLayoutListener(new GlobalLayoutListener());
}

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

public void saveActionViewStates(Bundle outStates) {
    SparseArray<Parcelable> viewStates = null;

    final int itemCount = size();
    for (int i = 0; i < itemCount; i++) {
        final MenuItem item = getItem(i);
        final View v = item.getActionView();
        if (v != null && v.getId() != View.NO_ID) {
            if (viewStates == null) {
                viewStates = new SparseArray<Parcelable>();
            }//  w  w w.  jav  a 2 s .c  o  m
            v.saveHierarchyState(viewStates);
        }
        if (item.hasSubMenu()) {
            final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu();
            subMenu.saveActionViewStates(outStates);
        }
    }

    if (viewStates != null) {
        outStates.putSparseParcelableArray(getActionViewStatesKey(), viewStates);
    }
}

From source file:com.frostwire.android.gui.activities.MainActivity.java

private SparseArray<DangerousPermissionsChecker> initPermissionsCheckers() {
    SparseArray<DangerousPermissionsChecker> checkers = new SparseArray<>();
    // EXTERNAL STORAGE ACCESS CHECKER.
    final DangerousPermissionsChecker externalStorageChecker = new DangerousPermissionsChecker(this,
            DangerousPermissionsChecker.EXTERNAL_STORAGE_PERMISSIONS_REQUEST_CODE);
    //externalStorageChecker.setPermissionsGrantedCallback(() -> {});
    checkers.put(DangerousPermissionsChecker.EXTERNAL_STORAGE_PERMISSIONS_REQUEST_CODE, externalStorageChecker);
    // COARSE/*from   w w w .  ja  va  2  s  . c o m*/
    final DangerousPermissionsChecker accessCoarseLocationChecker = new DangerousPermissionsChecker(this,
            DangerousPermissionsChecker.ACCESS_COARSE_LOCATION_PERMISSIONS_REQUEST_CODE);
    checkers.put(DangerousPermissionsChecker.ACCESS_COARSE_LOCATION_PERMISSIONS_REQUEST_CODE,
            accessCoarseLocationChecker);
    // add more permissions checkers if needed...
    return checkers;
}

From source file:org.indywidualni.centrumfm.util.ChangeLog.java

/**
 * Read the change log from an XML file.
 *
 * @param xml  The {@code XmlPullParser} instance used to read the change log.
 * @param full If {@code true} the full change log is read. Otherwise only the changes since the
 *             last (saved) version are read.
 * @return A {@code SparseArray} mapping the version codes to release information.
 *///from  ww w. j  av a  2 s.co m
protected SparseArray<ReleaseItem> readChangeLog(XmlPullParser xml, boolean full) {
    SparseArray<ReleaseItem> result = new SparseArray<>();

    try {
        int eventType = xml.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG && xml.getName().equals(ReleaseTag.NAME)) {
                if (parseReleaseTag(xml, full, result)) {
                    // Stop reading more elements if this entry is not newer than the last
                    // version.
                    break;
                }
            }
            eventType = xml.next();
        }
    } catch (XmlPullParserException | IOException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }

    return result;
}

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;//from w  w w  . j a  v a  2s .  com
    }

    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);
}