Example usage for android.util SparseArray get

List of usage examples for android.util SparseArray get

Introduction

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

Prototype

public E get(int key) 

Source Link

Document

Gets the Object mapped from the specified key, or null if no such mapping has been made.

Usage

From source file:com.atwal.wakeup.battery.util.Utilities.java

/**
 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
 *
 * @param bitmap  The bitmap to scan//from w ww .j a  va  2  s. co m
 * @param samples The approximate max number of samples to use.
 */
public static int findDominantColorByHue(Bitmap bitmap, int samples) {
    final int height = bitmap.getHeight();
    final int width = bitmap.getWidth();
    int sampleStride = (int) Math.sqrt((height * width) / samples);
    if (sampleStride < 1) {
        sampleStride = 1;
    }

    // This is an out-param, for getting the hsv values for an rgb
    float[] hsv = new float[3];

    // First get the best hue, by creating a histogram over 360 hue buckets,
    // where each pixel contributes a score weighted by saturation, value, and alpha.
    float[] hueScoreHistogram = new float[360];
    float highScore = -1;
    int bestHue = -1;

    for (int y = 0; y < height; y += sampleStride) {
        for (int x = 0; x < width; x += sampleStride) {
            int argb = bitmap.getPixel(x, y);
            int alpha = 0xFF & (argb >> 24);
            if (alpha < 0x80) {
                // Drop mostly-transparent pixels.
                continue;
            }
            // Remove the alpha channel.
            int rgb = argb | 0xFF000000;
            Color.colorToHSV(rgb, hsv);
            // Bucket colors by the 360 integer hues.
            int hue = (int) hsv[0];
            if (hue < 0 || hue >= hueScoreHistogram.length) {
                // Defensively avoid array bounds violations.
                continue;
            }
            float score = hsv[1] * hsv[2];
            hueScoreHistogram[hue] += score;
            if (hueScoreHistogram[hue] > highScore) {
                highScore = hueScoreHistogram[hue];
                bestHue = hue;
            }
        }
    }

    SparseArray<Float> rgbScores = new SparseArray<Float>();
    int bestColor = 0xff000000;
    highScore = -1;
    // Go theme_icon_back over the RGB colors that match the winning hue,
    // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
    // The highest-scoring RGB color wins.
    for (int y = 0; y < height; y += sampleStride) {
        for (int x = 0; x < width; x += sampleStride) {
            int rgb = bitmap.getPixel(x, y) | 0xff000000;
            Color.colorToHSV(rgb, hsv);
            int hue = (int) hsv[0];
            if (hue == bestHue) {
                float s = hsv[1];
                float v = hsv[2];
                int bucket = (int) (s * 100) + (int) (v * 10000);
                // Score by cumulative saturation * value.
                float score = s * v;
                Float oldTotal = rgbScores.get(bucket);
                float newTotal = oldTotal == null ? score : oldTotal + score;
                rgbScores.put(bucket, newTotal);
                if (newTotal > highScore) {
                    highScore = newTotal;
                    // All the colors in the winning bucket are very similar. Last in wins.
                    bestColor = rgb;
                }
            }
        }
    }
    return bestColor;
}

From source file:org.telegram.ui.Components.NumberPicker.java

private void ensureCachedScrollSelectorValue(int selectorIndex) {
    SparseArray<String> cache = mSelectorIndexToStringCache;
    String scrollSelectorValue = cache.get(selectorIndex);
    if (scrollSelectorValue != null) {
        return;//from   w w  w.  ja  v a  2s .  c om
    }
    if (selectorIndex < mMinValue || selectorIndex > mMaxValue) {
        scrollSelectorValue = "";
    } else {
        if (mDisplayedValues != null) {
            int displayedValueIndex = selectorIndex - mMinValue;
            scrollSelectorValue = mDisplayedValues[displayedValueIndex];
        } else {
            scrollSelectorValue = formatNumber(selectorIndex);
        }
    }
    cache.put(selectorIndex, scrollSelectorValue);
}

From source file:com.tzutalin.dlibtest.CameraConnectionFragment.java

/**
 * Sets up member variables related to camera.
 *
 * @param width  The width of available size for camera preview
 * @param height The height of available size for camera preview
 *///from  www.  java 2  s .  c  om
@DebugLog
@SuppressLint("LongLogTag")
private void setUpCameraOutputs(final int width, final int height) {
    final Activity activity = getActivity();
    final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        SparseArray<Integer> cameraFaceTypeMap = new SparseArray<>();
        // Check the facing types of camera devices
        for (final String cameraId : manager.getCameraIdList()) {
            final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
            final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
            if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
                if (cameraFaceTypeMap.get(CameraCharacteristics.LENS_FACING_FRONT) != null) {
                    cameraFaceTypeMap.append(CameraCharacteristics.LENS_FACING_FRONT,
                            cameraFaceTypeMap.get(CameraCharacteristics.LENS_FACING_FRONT) + 1);
                } else {
                    cameraFaceTypeMap.append(CameraCharacteristics.LENS_FACING_FRONT, 1);
                }
            }

            if (facing != null && facing == CameraCharacteristics.LENS_FACING_BACK) {
                if (cameraFaceTypeMap.get(CameraCharacteristics.LENS_FACING_FRONT) != null) {
                    cameraFaceTypeMap.append(CameraCharacteristics.LENS_FACING_BACK,
                            cameraFaceTypeMap.get(CameraCharacteristics.LENS_FACING_BACK) + 1);
                } else {
                    cameraFaceTypeMap.append(CameraCharacteristics.LENS_FACING_BACK, 1);
                }
            }
        }

        Integer num_facing_back_camera = cameraFaceTypeMap.get(CameraCharacteristics.LENS_FACING_BACK);
        for (final String cameraId : manager.getCameraIdList()) {
            final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
            final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
            // If facing back camera or facing external camera exist, we won't use facing front camera
            if (num_facing_back_camera != null && num_facing_back_camera > 0) {
                // We don't use a front facing camera in this sample if there are other camera device facing types
                if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
                    continue;
                }
            }

            final StreamConfigurationMap map = characteristics
                    .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

            if (map == null) {
                continue;
            }

            // For still image captures, we use the largest available size.
            final Size largest = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.YUV_420_888)),
                    new CompareSizesByArea());

            // Danger, W.R.! Attempting to use too large a preview size could  exceed the camera
            // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
            // garbage capture data.
            previewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, largest);

            // We fit the aspect ratio of TextureView to the size of preview we picked.
            final int orientation = getResources().getConfiguration().orientation;
            if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                textureView.setAspectRatio(previewSize.getWidth(), previewSize.getHeight());
            } else {
                textureView.setAspectRatio(previewSize.getHeight(), previewSize.getWidth());
            }

            CameraConnectionFragment.this.cameraId = cameraId;
            return;
        }
    } catch (final CameraAccessException e) {
        Timber.tag(TAG).e("Exception!", e);
    } catch (final NullPointerException e) {
        // Currently an NPE is thrown when the Camera2API is used but not supported on the
        // device this code runs.
        ErrorDialog.newInstance(getString(R.string.camera_error)).show(getChildFragmentManager(),
                FRAGMENT_DIALOG);
    }
}

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

From source file:com.fuzz.indicator.CutoutViewIndicator.java

/**
 * Utility method for invalidating the {@link #generator} (so to speak).
 * <p>//from  ww w  .j  a va 2  s  .  com
 *     It'll ensure that the child views match both what the current
 *     {@link CutoutCellGenerator} creates AND the params defined by
 *     {@link #defaultChildParams}.
 * </p>
 * Views which have been marked for
 * {@link CutoutViewLayoutParams#preservedDuringRebuild preservation} will
 * not be replaced.
 */
public void rebuildChildViews() {
    SparseArray<CutoutCell> preserved = cells.clone();
    cells.clear();
    for (int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);
        if (((CutoutViewLayoutParams) child.getLayoutParams()).preservedDuringRebuild) {
            cells.put(i, preserved.get(i));
        }
    }
    preserved.clear();
    removeAllViews();
    dataSetObserver.onChanged();
}

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

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

    Bundle arguments = getArguments();/*from w ww .j ava2  s  .co  m*/
    if (arguments != null) {
        mGroupId = arguments.getString(ARG_GROUP_ID);
        mType = arguments.getInt(ARG_TYPE);
        //noinspection unchecked
        mItems = (List<Item>) arguments.getSerializable(ARG_ITEMS);
        mFilter = arguments.getString(ARG_FILTER);
    }

    if (mItems == null) {
        DbHelper db = DbHelper.getInstance(getActivity());

        mItems = new ArrayList<>();
        Table<Organization> organizationsTable = db.getTableFor(Organization.class);
        try {
            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<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];

                Item item = null;
                if (mType == GROUPED) {
                    if (!group.name.equals(lastTitle)) {
                        if (mGroupId != null && mGroupPosition == -1 && mGroupId.equals(group.position))
                            mGroupPosition = pos;
                        mItems.add(new Item(group.name));
                        ++pos;
                        lastTitle = group.name;
                    }
                } else {
                    item = itemsCache.get(organization.id);
                }

                if (item == null) {
                    item = new Item(group, place, organization);
                    item.placesStr = place.name;
                    mItems.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();
        }
    }

    mAdapter = new OrganizationsAdapter(getActivity());
    if (mGroupPosition != -1) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                mListView.setSelection(mGroupPosition);
                if (mFilter != null)
                    onQueryTextChange(mFilter);
            }
        });
    }
}

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 {//from w w  w. java2 s  .  c o m
        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.android.messaging.mmslib.pdu.PduPersister.java

/**
 * For a given address type, extract the recipients from the headers.
 *
 * @param addressType     can be PduHeaders.FROM or PduHeaders.TO
 * @param recipients      a HashSet that is loaded with the recipients from the FROM or TO
 *                        headers//from w  w  w  .  j  av  a 2 s .  c  o  m
 * @param addressMap      a HashMap of the addresses from the ADDRESS_FIELDS header
 */
private void loadRecipients(final int addressType, final HashSet<String> recipients,
        final SparseArray<EncodedStringValue[]> addressMap) {
    final EncodedStringValue[] array = addressMap.get(addressType);
    if (array == null) {
        return;
    }
    for (final EncodedStringValue v : array) {
        if (v != null) {
            final String number = v.getString();
            if (!recipients.contains(number)) {
                // Only add numbers which aren't already included.
                recipients.add(number);
            }
        }
    }
}

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

/**
 * For a given address type, extract the recipients from the headers.
 *
 * @param recipients      a HashSet that is loaded with the recipients from the FROM or TO
 *                        headers//from  w w w  . j a va2s .c o  m
 * @param addressMap      a HashMap of the addresses from the ADDRESS_FIELDS header
 * @param selfNumber      self phone number
 */
private void checkAndLoadToCcRecipients(final HashSet<String> recipients,
        final SparseArray<EncodedStringValue[]> addressMap, final String selfNumber) {
    final EncodedStringValue[] arrayTo = addressMap.get(PduHeaders.TO);
    final EncodedStringValue[] arrayCc = addressMap.get(PduHeaders.CC);
    final ArrayList<String> numbers = new ArrayList<String>();
    if (arrayTo != null) {
        for (final EncodedStringValue v : arrayTo) {
            if (v != null) {
                numbers.add(v.getString());
            }
        }
    }
    if (arrayCc != null) {
        for (final EncodedStringValue v : arrayCc) {
            if (v != null) {
                numbers.add(v.getString());
            }
        }
    }
    for (final String number : numbers) {
        // Only add numbers which aren't my own number.
        if (TextUtils.isEmpty(selfNumber) || !PhoneNumberUtils.compare(number, selfNumber)) {
            if (!recipients.contains(number)) {
                // Only add numbers which aren't already included.
                recipients.add(number);
            }
        }
    }
}

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

private void dispatchRestoreInstanceState(Bundle state) {
    SparseArray<Parcelable> presenterStates = state.getSparseParcelableArray(PRESENTER_KEY);

    if (presenterStates == null || mPresenters.isEmpty())
        return;//  w ww. j a  v  a 2  s  . c o m

    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) {
                Parcelable parcel = presenterStates.get(id);
                if (parcel != null) {
                    presenter.onRestoreInstanceState(parcel);
                }
            }
        }
    }
}