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:com.wit.android.support.fragment.manage.BaseFragmentFactory.java

/**
 * Creates a new instance of BaseFragmentFactory. If {@link com.wit.android.support.fragment.annotation.FactoryFragments @FactoryFragments}
 * or {@link com.wit.android.support.fragment.annotation.FragmentFactories @FragmentFactories}
 * annotations are presented above a sub-class of this BaseFragmentFactory, they will be processed
 * here.//from   www.  ja  v a 2  s.c o m
 */
public BaseFragmentFactory() {
    final Class<?> classOfFactory = ((Object) this).getClass();
    /**
     * Process class annotations.
     */
    final SparseArray<FragmentItem> items = new SparseArray<>();
    // Obtain fragment ids.
    if (classOfFactory.isAnnotationPresent(FactoryFragments.class)) {
        final FactoryFragments fragments = classOfFactory.getAnnotation(FactoryFragments.class);

        final int[] ids = fragments.value();
        if (ids.length > 0) {
            for (int id : ids) {
                items.put(id, new FragmentItem(id, getFragmentTag(id), null));
            }
        }
    }
    this.processAnnotatedFragments(classOfFactory, items);
    if (items.size() > 0) {
        this.mItems = items;
    }
    // Obtain joined factories.
    final List<Class<? extends FragmentController.FragmentFactory>> factories = this.gatherJoinedFactories(
            classOfFactory, new ArrayList<Class<? extends FragmentController.FragmentFactory>>());
    if (!factories.isEmpty()) {
        for (Class<? extends FragmentController.FragmentFactory> factory : factories) {
            FragmentController.FragmentFactory fragmentFactory = null;
            try {
                fragmentFactory = factory.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                Log.e(TAG, "Failed to instantiate the fragment factory class of(" + factory.getSimpleName()
                        + ")." + "Make sure this fragment factory has public empty constructor.", e);
            }
            if (fragmentFactory != null) {
                joinFactory(fragmentFactory);
            }
        }
    }
}

From source file:com.dgsd.android.ShiftTracker.Adapter.WeekAdapter.java

@Override
public Cursor swapCursor(Cursor cursor) {
    clearCaches();/*from   w  w  w .j  ava2  s. c  om*/

    if (cursor == null)
        return super.swapCursor(null);

    MatrixCursor mc = new MatrixCursor(DbTable.SHIFTS.getFieldNames(), cursor.getCount() + 7);

    int jd = mStartingJulianDay;
    final int colCount = cursor.getColumnCount();

    SparseArray<List<Object[]>> jdToRowArray = new SparseArray<List<Object[]>>();

    if (cursor.moveToFirst()) {
        final int jdIndex = cursor.getColumnIndex(DbField.JULIAN_DAY.name);
        do {
            Object[] row = new Object[colCount];
            for (int i = 0; i < colCount; i++)
                row[i] = cursor.getString(i);

            final int shiftDay = cursor.getInt(jdIndex);

            List<Object[]> rowsOnSameJd = jdToRowArray.get(shiftDay, null);
            if (rowsOnSameJd == null)
                rowsOnSameJd = new ArrayList<Object[]>();

            rowsOnSameJd.add(row);

            jdToRowArray.put(shiftDay, rowsOnSameJd);
        } while (cursor.moveToNext());
    }

    for (int i = jd; i < jd + 7; i++) {
        List<Object[]> rows = jdToRowArray.get(i);
        if (rows != null)
            for (Object[] row : rows)
                mc.addRow(row);

        //Add a 'Add Shift' row
        Object[] row = new Object[colCount];
        row[0] = mRand.nextInt(Integer.MAX_VALUE); // DbField.ID
        row[1] = i; // DbField.JULIAN_DAY
        row[2] = i; // DbField.END_JULIAN_DAY
        row[3] = -1; // DbField.START_TIME
        row[4] = -1; // DbField.END_TIME
        row[5] = -1; // DbField.PAY_RATE
        row[6] = NEW_ROW_KEY; // DbField.NAME
        row[7] = null; // DbField.NOTE
        row[8] = -1; // DbField.BREAK_DURATION
        row[9] = 0; // DbField.IS_TEMPLATE
        row[10] = -1; // DbField.REMINDER

        mc.addRow(row);
    }

    return super.swapCursor(mc);
}

From source file:fr.cph.chicago.core.fragment.NearbyFragment.java

private void loadAroundBusArrivals(@NonNull final BusStop busStop,
        @NonNull final SparseArray<Map<String, List<BusArrival>>> busArrivalsMap) {
    try {//from   w  ww .  j  a  v a 2s.  com
        if (isAdded()) {
            final CtaConnect cta = CtaConnect.getInstance(getContext());
            int busStopId = busStop.getId();
            // Create
            final Map<String, List<BusArrival>> tempMap = busArrivalsMap.get(busStopId,
                    new ConcurrentHashMap<>());
            if (!tempMap.containsKey(Integer.toString(busStopId))) {
                busArrivalsMap.put(busStopId, tempMap);
            }

            final MultiValuedMap<String, String> reqParams = new ArrayListValuedHashMap<>(1, 1);
            reqParams.put(requestStopId, Integer.toString(busStopId));
            final InputStream is = cta.connect(BUS_ARRIVALS, reqParams);
            final XmlParser xml = XmlParser.getInstance();
            final List<BusArrival> busArrivals = xml.parseBusArrivals(is);
            for (final BusArrival busArrival : busArrivals) {
                final String direction = busArrival.getRouteDirection();
                if (tempMap.containsKey(direction)) {
                    final List<BusArrival> temp = tempMap.get(direction);
                    temp.add(busArrival);
                } else {
                    final List<BusArrival> temp = new ArrayList<>();
                    temp.add(busArrival);
                    tempMap.put(direction, temp);
                }
            }
            trackWithGoogleAnalytics(activity, R.string.analytics_category_req,
                    R.string.analytics_action_get_bus, BUSES_ARRIVAL_URL, 0);
        }
    } catch (final Throwable throwable) {
        throw Exceptions.propagate(throwable);
    }
}

From source file:com.sonymobile.androidapp.gridcomputing.fragments.ReportChartFragment.java

/**
 * Groups the original values into a sparse array.
 * The outer sparse array is indexed by the group field.
 * The inner sparse array is indexed by the index field.
 * If groupField and indexField are the same, then the outer sparse array contains only 1 entry
 * index by 0 and the inner sparse array is indexed by indexField.
 * @param original the original value returned from the SQL query.
 * @param groupField the field used to group the outer sparse array.
 * @param indexField the field used to group the inner sparse array.
 * @return a bidimensional sparse array indexed by  groupField and indexField.
 *///w w w.  j a va  2 s  .  c o m
private SparseArray<SparseArray<Double>> groupValues(final SparseArray<Pair<Date, Double>> original,
        final int groupField, final int indexField) {
    final Calendar calendar = Calendar.getInstance();
    final SparseArray<SparseArray<Double>> weeks = new SparseArray<>();

    for (int i = 0; i < original.size(); i++) {
        try {
            final int key = original.keyAt(i);

            calendar.setTime(original.get(key).first);
            final double value = original.get(key).second;

            final int indexValue = calendar.get(indexField);
            final int groupValue = groupField == indexField ? 0 : calendar.get(groupField);

            SparseArray<Double> currentWeek = weeks.get(groupValue);
            if (currentWeek == null) {
                currentWeek = new SparseArray<>();
                weeks.put(groupValue, currentWeek);
            }
            currentWeek.put(indexValue, value);
        } catch (Exception e) {
            Log.e(e.getMessage());
        }
    }

    // normalize the data
    // if the index field is DAY_OF_WEEK, then we'll add the remaining days to fill
    // the week from sunday until saturday
    if (indexField == Calendar.DAY_OF_WEEK) {
        for (int i = 0; i < weeks.size(); i++) {
            final int key = weeks.keyAt(i);
            SparseArray<Double> currentWeek = weeks.get(key);
            for (int j = Calendar.SUNDAY; j <= Calendar.SATURDAY; j++) {
                if (currentWeek.get(j) == null) {
                    currentWeek.put(j, 0.0);
                }
            }
        }
    }

    return weeks;
}

From source file:com.wit.android.support.fragment.manage.BaseFragmentFactory.java

/**
 * Processes all annotated fields marked with {@link com.wit.android.support.fragment.annotation.FactoryFragment @FactoryFragment}
 * annotation and puts them into the given <var>items</var> array.
 *
 * @param classOfFactory Class of this fragment factory.
 * @param items          Initial array of fragment items.
 *//*  www  .ja  v a  2s  .co  m*/
@SuppressWarnings("unchecked")
private void processAnnotatedFragments(final Class<?> classOfFactory, final SparseArray<FragmentItem> items) {
    FragmentAnnotations.iterateFields(classOfFactory, new FragmentAnnotations.FieldProcessor() {

        /**
         */
        @Override
        public void onProcessField(@NonNull Field field, @NonNull String name) {
            if (field.isAnnotationPresent(FactoryFragment.class) && int.class.equals(field.getType())) {
                final FactoryFragment factoryFragment = field.getAnnotation(FactoryFragment.class);
                try {
                    final int id = (int) field.get(BaseFragmentFactory.this);
                    items.put(id, new FragmentItem(id, TextUtils.isEmpty(factoryFragment.taggedName())
                            ? getFragmentTag(id)
                            : createFragmentTag(
                                    (Class<? extends FragmentController.FragmentFactory>) classOfFactory,
                                    factoryFragment.taggedName()),
                            factoryFragment.type()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

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//w w w. j  a  v a2s. c om
 * @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:de.skubware.opentraining.activity.settings.sync.WgerJSONParser.java

/**
 * A generic parsing method for parsing JSON to SportsEquipment, Muscle or Locale.
 */// ww  w  .java 2s .c om
private static <T> SparseArray<T> parse(String jsonString, Class<T> c) throws JSONException {
    JSONObject mainObject = new JSONObject(jsonString);
    Log.d(TAG, "jsonString: " + mainObject.toString());
    JSONArray mainArray = mainObject.getJSONArray("objects");

    SparseArray<T> sparseArray = new SparseArray<T>();

    // parse each exercise of the JSON Array
    for (int i = 0; i < mainArray.length(); i++) {
        JSONObject singleObject = mainArray.getJSONObject(i);

        Integer id = singleObject.getInt("id");
        Object parsedObject;
        if (c.equals(Muscle.class)) {
            // handle Muscles
            String name = singleObject.getString("name");
            parsedObject = mDataProvider.getMuscleByName(name);

            if (parsedObject == null)
                Log.e(TAG, "Could not find Muscle: " + name);

        } else if (c.equals(SportsEquipment.class)) {
            // handle SportsEquipment
            String name = singleObject.getString("name");
            parsedObject = mDataProvider.getEquipmentByName(name);

            if (parsedObject == null)
                Log.e(TAG, "Could not find SportsEquipment: " + name);

        } else if (c.equals(Locale.class)) {
            // handle Locales
            String short_name = singleObject.getString("short_name");
            parsedObject = new Locale(short_name);

            if (short_name == null || short_name.equals(""))
                Log.e(TAG, "Error, no short_name=" + short_name);

        } else if (c.equals(LicenseType.class)) {
            // handle licenses
            String short_name = singleObject.getString("short_name");

            parsedObject = mDataProvider.getLicenseTypeByName(short_name);

            if (short_name == null || short_name.equals(""))
                Log.e(TAG, "Error, no short_name=" + short_name);

        } else {
            throw new IllegalStateException(
                    "parse(String, Class<T>) cannot be applied for class: " + c.toString());
        }

        sparseArray.put(id, (T) parsedObject);

    }

    return sparseArray;
}

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 .j av a  2s.c  om*/
    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:fr.cph.chicago.core.fragment.NearbyFragment.java

private SparseArray<TrainArrival> loadAroundTrainArrivals(@NonNull final List<Station> trainStations) {
    try {/*from w w w  .j av  a2 s .c  o m*/
        final SparseArray<TrainArrival> trainArrivals = new SparseArray<>();
        if (isAdded()) {
            final CtaConnect cta = CtaConnect.getInstance(getContext());
            for (final Station station : trainStations) {
                final MultiValuedMap<String, String> reqParams = new ArrayListValuedHashMap<>(1, 1);
                reqParams.put(requestMapId, Integer.toString(station.getId()));
                final InputStream xmlRes = cta.connect(TRAIN_ARRIVALS, reqParams);
                final XmlParser xml = XmlParser.getInstance();
                final SparseArray<TrainArrival> temp = xml.parseArrivals(xmlRes,
                        DataHolder.getInstance().getTrainData());
                for (int j = 0; j < temp.size(); j++) {
                    trainArrivals.put(temp.keyAt(j), temp.valueAt(j));
                }
                trackWithGoogleAnalytics(activity, R.string.analytics_category_req,
                        R.string.analytics_action_get_train, TRAINS_ARRIVALS_URL, 0);
            }
        }
        return trainArrivals;
    } catch (final Throwable throwable) {
        throw Exceptions.propagate(throwable);
    }
}

From source file:com.github.paradam.support.v4.infinitepager.InfiniteFragmentStatePagerAdapter.java

@Override
public void notifyDataSetChanged() {
    onPreNotifyDataSetChange();/*from ww w .  j a v  a2 s  .  co  m*/
    final int count = getRelativeCount();
    final int margin = getMargin();

    ArrayList<Fragment.SavedState> newSavedState = new ArrayList<Fragment.SavedState>(count);
    ArrayList<Fragment> newFragments = new ArrayList<Fragment>(count);
    SparseArray<Fragment> newDestroyedFragments = new SparseArray<Fragment>();

    int length = mFragments.size();

    for (int x = 0; x < length; x++) {
        Fragment fragment = mFragments.get(x);
        boolean fromDestroyed = false;
        if (fragment == null) {
            // Check if there is a destroyed fragment that was in the list, use that if there is.
            fragment = mDestroyedFragments.get(x);
            fromDestroyed = true;
        }
        int position = getItemPosition(fragment);
        switch (position) {
        case POSITION_UNCHANGED:
            while (newFragments.size() < x + 1) {
                newFragments.add(null);
                newSavedState.add(null);
            }
            if (!fromDestroyed) {
                newFragments.set(x, mFragments.get(x));
            } else {
                newDestroyedFragments.put(x, fragment);
            }
            if (mSavedState.size() > x) {
                newSavedState.set(x, mSavedState.get(x));
            }
            break;
        case POSITION_NONE:
            // Do not add fragment.
            if (!fromDestroyed) {
                if (mCurTransaction == null) {
                    mCurTransaction = mFragmentManager.beginTransaction();
                }
                mCurTransaction.remove(mFragments.get(x));
            }
            break;
        default:
            position = (position - margin + count) % count;
            while (newFragments.size() < position + 1) {
                newFragments.add(null);
                newSavedState.add(null);
            }
            if (!fromDestroyed) {
                newFragments.set(position, fragment);
            } else {
                newDestroyedFragments.put(position, fragment);
            }
            if (mSavedState.size() > x) {
                newSavedState.set(position, mSavedState.get(x));
            }
        }
    }

    mSavedState = newSavedState;
    mFragments = newFragments;
    mDestroyedFragments = newDestroyedFragments;

    super.notifyDataSetChanged();
}