Example usage for android.util SparseArray size

List of usage examples for android.util SparseArray size

Introduction

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

Prototype

public int size() 

Source Link

Document

Returns the number of key-value mappings that this SparseArray currently stores.

Usage

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

/**
 * Destroys all loaders with the specified invocation class and the specified inputs.
 *
 * @param context         the context.//w ww.ja v a 2s  .c  o m
 * @param loaderId        the loader ID.
 * @param invocationClass the invocation class.
 * @param invocationArgs  the invocation constructor arguments.
 * @param inputs          the invocation inputs.
 */
@SuppressWarnings("unchecked")
static void purgeLoader(@Nonnull final Object context, final int loaderId,
        @Nonnull final Class<?> invocationClass, @Nonnull final Object[] invocationArgs,
        @Nonnull final List<?> inputs) {

    final SparseArray<WeakReference<RoutineLoaderCallbacks<?>>> callbackArray = sCallbackMap.get(context);

    if (callbackArray == null) {

        return;
    }

    final LoaderManager loaderManager;

    if (context instanceof FragmentActivity) {

        final FragmentActivity activity = (FragmentActivity) context;
        loaderManager = activity.getSupportLoaderManager();

    } else if (context instanceof Fragment) {

        final Fragment fragment = (Fragment) context;
        loaderManager = fragment.getLoaderManager();

    } else {

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

    int i = 0;

    while (i < callbackArray.size()) {

        final RoutineLoaderCallbacks<?> callbacks = callbackArray.valueAt(i).get();

        if (callbacks == null) {

            callbackArray.remove(callbackArray.keyAt(i));
            continue;
        }

        final RoutineLoader<Object, Object> loader = (RoutineLoader<Object, Object>) callbacks.mLoader;

        if ((loader.getInvocationType() == invocationClass)
                && Arrays.equals(loader.getInvocationArgs(), invocationArgs)
                && (loader.getInvocationCount() == 0)) {

            final int id = callbackArray.keyAt(i);

            if (((loaderId == ContextRoutineBuilder.AUTO) || (loaderId == id))
                    && loader.areSameInputs(inputs)) {

                loaderManager.destroyLoader(id);
                callbackArray.remove(id);
                continue;
            }
        }

        ++i;
    }

    if (callbackArray.size() == 0) {

        sCallbackMap.remove(context);
    }
}

From source file:fr.cph.chicago.task.GlobalConnectTask.java

@Override
protected final Boolean doInBackground(final Void... connects) {
    mTrainBoolean = true;/*from  w w  w  .  j av  a2  s .c  om*/
    mBusBoolean = true;
    mBikeBoolean = true;
    mNetworkAvailable = Util.isNetworkAvailable();
    if (mNetworkAvailable) {
        CtaConnect ctaConnect = CtaConnect.getInstance();
        DivvyConnect divvyConnect = DivvyConnect.getInstance();
        if (mLoadTrains) {
            try {
                for (Entry<String, Object> entry : mParams.entrySet()) {
                    String key = entry.getKey();
                    if (key.equals("mapid")) {
                        Object value = entry.getValue();
                        if (value instanceof String) {
                            String xmlResult = ctaConnect.connect(mRequestType, mParams);
                            this.mTrainArrivals = mXml.parseArrivals(xmlResult, mData);
                        } else if (value instanceof List) {
                            @SuppressWarnings("unchecked")
                            List<String> list = (List<String>) value;
                            if (list.size() < 5) {
                                String xmlResult = ctaConnect.connect(mRequestType, mParams);
                                this.mTrainArrivals = mXml.parseArrivals(xmlResult, mData);
                            } else {
                                int size = list.size();
                                SparseArray<TrainArrival> tempArrivals = new SparseArray<TrainArrival>();
                                int start = 0;
                                int end = 4;
                                while (end < size + 1) {
                                    List<String> subList = list.subList(start, end);
                                    MultiMap<String, String> paramsTemp = new MultiValueMap<String, String>();
                                    for (String sub : subList) {
                                        paramsTemp.put(key, sub);
                                    }

                                    String xmlResult = ctaConnect.connect(mRequestType, paramsTemp);
                                    SparseArray<TrainArrival> temp = mXml.parseArrivals(xmlResult, mData);
                                    for (int j = 0; j < temp.size(); j++) {
                                        tempArrivals.put(temp.keyAt(j), temp.valueAt(j));
                                    }
                                    start = end;
                                    if (end + 3 >= size - 1 && end != size) {
                                        end = size;
                                    } else {
                                        end = end + 3;
                                    }
                                }
                                this.mTrainArrivals = tempArrivals;
                            }
                        }
                    }
                }

                // Apply filters
                int index = 0;
                while (index < mTrainArrivals.size()) {
                    TrainArrival arri = mTrainArrivals.valueAt(index++);
                    List<Eta> etas = arri.getEtas();
                    // Sort Eta by arriving time
                    Collections.sort(etas);
                    // Copy data into new list to be able to avoid looping on a list that we want to
                    // modify
                    List<Eta> etas2 = new ArrayList<Eta>();
                    etas2.addAll(etas);
                    int j = 0;
                    Eta eta = null;
                    Station station = null;
                    TrainLine line = null;
                    TrainDirection direction = null;
                    for (int i = 0; i < etas2.size(); i++) {
                        eta = etas2.get(i);
                        station = eta.getStation();
                        line = eta.getRouteName();
                        direction = eta.getStop().getDirection();
                        boolean toRemove = Preferences.getTrainFilter(station.getId(), line, direction);
                        if (!toRemove) {
                            etas.remove(i - j++);
                        }
                    }
                }

            } catch (ConnectException e) {
                mTrainBoolean = false;
                this.mTrackerTrainException = e;
            } catch (ParserException e) {
                mTrainBoolean = false;
                this.mTrackerTrainException = e;
            }
        }
        if (mLoadBuses) {
            try {
                List<String> rts = new ArrayList<String>();
                List<String> stpids = new ArrayList<String>();
                for (Entry<String, Object> entry : mParams2.entrySet()) {
                    String key = entry.getKey();
                    StringBuilder str = new StringBuilder();
                    int i = 0;
                    @SuppressWarnings("unchecked")
                    List<String> values = (ArrayList<String>) entry.getValue();
                    for (String v : values) {
                        str.append(v + ",");
                        if (i == 9 || i == values.size() - 1) {
                            if (key.equals("rt")) {
                                rts.add(str.toString());
                            } else if (key.equals("stpid")) {
                                stpids.add(str.toString());
                            }
                            str = new StringBuilder();
                            i = -1;
                        }
                        i++;
                    }
                }
                for (int i = 0; i < rts.size(); i++) {
                    MultiMap<String, String> para = new MultiValueMap<String, String>();
                    para.put("rt", rts.get(i));
                    para.put("stpid", stpids.get(i));
                    String xmlResult = ctaConnect.connect(mRequestType2, para);
                    this.mBusArrivals.addAll(mXml.parseBusArrivals(xmlResult));
                }
            } catch (ConnectException e) {
                mBusBoolean = false;
                this.mTrackerBusException = e;
            } catch (ParserException e) {
                mBusBoolean = false;
                this.mTrackerBusException = e;
            }
        }
        if (mLoadBikes) {
            try {
                String bikeContent = divvyConnect.connect();
                this.mBikeStations = mJson.parseStations(bikeContent);
                Collections.sort(this.mBikeStations, Util.BIKE_COMPARATOR_NAME);
            } catch (ParserException e) {
                mBikeBoolean = false;
                this.mTrackerBikeException = e;
            } catch (ConnectException e) {
                mBikeBoolean = false;
                this.mTrackerBikeException = e;
            } finally {
                if (!(mBusBoolean && mTrainBoolean)) {
                    if (mParams2.size() == 0 && mBusBoolean) {
                        mBusBoolean = false;
                    }
                    if (mParams.size() == 0 && mTrainBoolean) {
                        mTrainBoolean = false;
                    }
                }
            }
        }
        return mTrainBoolean || mBusBoolean || mBikeBoolean;
    } else {
        return mNetworkAvailable;
    }
}

From source file:bolts.AppLinkNavigation.java

/**
 * Gets a JSONObject-compatible value for the given object.
 *///  w  ww. j  a v a  2 s .  c  o  m
private Object getJSONValue(Object value) throws JSONException {
    if (value instanceof Bundle) {
        return getJSONForBundle((Bundle) value);
    } else if (value instanceof CharSequence) {
        return value.toString();
    } else if (value instanceof List) {
        JSONArray array = new JSONArray();
        for (Object listValue : (List<?>) value) {
            array.put(getJSONValue(listValue));
        }
        return array;
    } else if (value instanceof SparseArray) {
        JSONArray array = new JSONArray();
        SparseArray<?> sparseValue = (SparseArray<?>) value;
        for (int i = 0; i < sparseValue.size(); i++) {
            array.put(sparseValue.keyAt(i), getJSONValue(sparseValue.valueAt(i)));
        }
        return array;
    } else if (value instanceof Character) {
        return value.toString();
    } else if (value instanceof Boolean) {
        return value;
    } else if (value instanceof Number) {
        if (value instanceof Double || value instanceof Float) {
            return ((Number) value).doubleValue();
        } else {
            return ((Number) value).longValue();
        }
    } else if (value instanceof boolean[]) {
        JSONArray array = new JSONArray();
        for (boolean arrValue : (boolean[]) value) {
            array.put(getJSONValue(arrValue));
        }
        return array;
    } else if (value instanceof char[]) {
        JSONArray array = new JSONArray();
        for (char arrValue : (char[]) value) {
            array.put(getJSONValue(arrValue));
        }
        return array;
    } else if (value instanceof CharSequence[]) {
        JSONArray array = new JSONArray();
        for (CharSequence arrValue : (CharSequence[]) value) {
            array.put(getJSONValue(arrValue));
        }
        return array;
    } else if (value instanceof double[]) {
        JSONArray array = new JSONArray();
        for (double arrValue : (double[]) value) {
            array.put(getJSONValue(arrValue));
        }
        return array;
    } else if (value instanceof float[]) {
        JSONArray array = new JSONArray();
        for (float arrValue : (float[]) value) {
            array.put(getJSONValue(arrValue));
        }
        return array;
    } else if (value instanceof int[]) {
        JSONArray array = new JSONArray();
        for (int arrValue : (int[]) value) {
            array.put(getJSONValue(arrValue));
        }
        return array;
    } else if (value instanceof long[]) {
        JSONArray array = new JSONArray();
        for (long arrValue : (long[]) value) {
            array.put(getJSONValue(arrValue));
        }
        return array;
    } else if (value instanceof short[]) {
        JSONArray array = new JSONArray();
        for (short arrValue : (short[]) value) {
            array.put(getJSONValue(arrValue));
        }
        return array;
    } else if (value instanceof String[]) {
        JSONArray array = new JSONArray();
        for (String arrValue : (String[]) value) {
            array.put(getJSONValue(arrValue));
        }
        return array;
    }
    return null;
}

From source file:com.google.android.gms.oem.bolti.keszlet.BarcodeCaptureActivity.java

/**
 * Creates and starts the camera.  Note that this uses a higher resolution in comparison
 * to other detection examples to enable the barcode detector to detect small barcodes
 * at long distances./*from www.  j  a va  2 s .  c o m*/
 *
 * Suppressing InlinedApi since there is a check that the minimum version is met before using
 * the constant.
 */
@SuppressLint("InlinedApi")
private void createCameraSource(boolean autoFocus, boolean useFlash) {
    Context context = getApplicationContext();

    // A barcode detector is created to track barcodes.  An associated multi-processor instance
    // is set to receive the barcode detection results, track the barcodes, and maintain
    // graphics for each barcode on screen.  The factory is used by the multi-processor to
    // create a separate tracker instance for each barcode.
    BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).build();
    BarcodeDetector barcodeDetector2 = new BarcodeDetector.Builder(context).build();
    BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay);

    //barcodeDetector.setProcessor(
    //        new MultiProcessor.Builder<>(barcodeFactory).build());

    barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
        @Override
        public void release() {
        }

        @Override
        public void receiveDetections(Detector.Detections<Barcode> detections) {
            final SparseArray<Barcode> barcodes = detections.getDetectedItems();
            //MediaPlayer mp = MediaPlayer.create(this, R.raw.sound);
            if (barcodes.size() != 0) {

                //  mp.start();
                barcode3 = barcodes.valueAt(0).displayValue;
                Log.w(TAG, barcode3);
                Intent data = new Intent();
                data.putExtra(BarcodeObject, barcode3);
                setResult(CommonStatusCodes.SUCCESS, data);
                finish();
            }
        }

    });

    if (!barcodeDetector.isOperational()) {
        // Note: The first time that an app using the barcode or face API is installed on a
        // device, GMS will download a native libraries to the device in order to do detection.
        // Usually this completes before the app is run for the first time.  But if that
        // download has not yet completed, then the above call will not detect any barcodes
        // and/or faces.
        //
        // isOperational() can be used to check if the required native libraries are currently
        // available.  The detectors will automatically become operational once the library
        // downloads complete on device.
        Log.w(TAG, "A Detektor fggsgei nem teljesthetk");

        // Check for low storage.  If there is low storage, the native library will not be
        // downloaded, so detection will not become operational.
        IntentFilter lowstorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
        boolean hasLowStorage = registerReceiver(null, lowstorageFilter) != null;

        if (hasLowStorage) {
            Toast.makeText(this, R.string.low_storage_error, Toast.LENGTH_LONG).show();
            Log.w(TAG, getString(R.string.low_storage_error));
        }

    }

    // Creates and starts the camera.  Note that this uses a higher resolution in comparison
    // to other detection examples to enable the barcode detector to detect small barcodes
    // at long distances.
    CameraSource.Builder builder = new CameraSource.Builder(getApplicationContext(), barcodeDetector)
            .setFacing(CameraSource.CAMERA_FACING_BACK).setRequestedPreviewSize(1600, 1024)
            .setRequestedFps(15.0f);

    // make sure that auto focus is an available option
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        builder = builder.setFocusMode(autoFocus ? Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE : null);
    }

    mCameraSource = builder.setFlashMode(useFlash ? Camera.Parameters.FLASH_MODE_TORCH : null).build();

}

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

/**
 * Creates a line data set to plot the chart.
 * @param setPosition this dataset position.
 * @param label The label of the data set.
 * @param array The sparse array containing the data to plot.
 * @param startValue the value at which the x axis starts.
 * @return a dataset ready to plot./*  www.ja  va 2 s. c o  m*/
 */
private LineDataSet getData(final int setPosition, final String label, final SparseArray<Double> array,
        final int startValue) {
    final List<Entry> values = new ArrayList<>();

    final int startIndex = startValue == 0 ? 0 : array.indexOfKey(startValue);

    for (int i = startIndex; i < array.size(); i++) {
        int key = array.keyAt(i);
        int xValue = startValue == 0 ? key : values.size() + startValue;
        values.add(new Entry(xValue, array.get(key).floatValue()));
    }
    for (int i = 0; i < startIndex; i++) {
        try {
            int key = array.keyAt(i);
            int xValue = startValue == 0 ? key : values.size() + startValue;
            values.add(new Entry(xValue, array.get(key).floatValue()));
        } catch (Exception e) {
            Log.e("Entry at index " + i + " does not exist");
        }
    }

    LineDataSet d = new LineDataSet(values, label);
    d.setLineWidth(2.5f);
    d.setCircleRadius(4f);
    d.setDrawValues(false);

    int color = CHART_COLORS[setPosition];
    d.setColor(color);
    d.setCircleColor(color);
    d.setDrawFilled(true);
    return d;
}

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

private SparseArray<TrainArrival> loadAroundTrainArrivals(@NonNull final List<Station> trainStations) {
    try {//from   ww  w.  j  a va  2s.  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.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 ww  .jav  a  2  s.co 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.tmall.wireless.tangram3.dataparser.concrete.PojoGroupBasicAdapter.java

@Override
protected void diffGroup(SparseArray<Card> added, SparseArray<Card> removed) {
    for (int i = 0, size = removed.size(); i < size; i++) {
        int key = removed.keyAt(i);
        Card card = removed.get(key);// w ww.jav  a2s  . c o  m
        if (card != null) {
            try {
                card.removed();
            } catch (Exception e) {
                if (card.serviceManager != null) {
                    CellSupport cellSupport = card.serviceManager.getService(CellSupport.class);
                    if (card.extras != null) {
                        cellSupport.onException(card.extras.toString(), e);
                    } else {
                        cellSupport.onException(card.stringType, e);
                    }
                }
            }
        }
    }

    for (int i = 0, size = added.size(); i < size; i++) {
        int key = added.keyAt(i);
        Card card = added.get(key);
        if (card != null) {
            try {
                card.added();
            } catch (Exception e) {
                if (card.serviceManager != null) {
                    CellSupport cellSupport = card.serviceManager.getService(CellSupport.class);
                    if (card.extras != null) {
                        cellSupport.onException(card.extras.toString(), e);
                    } else {
                        cellSupport.onException(card.stringType, e);
                    }
                }
            }
        }
    }
}

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

/**
 * Returns the merged change log./*from   w ww  .  ja v  a2  s  .c o m*/
 *
 * @param full If this is {@code true} the full change log is returned. Otherwise only changes for
 *             versions newer than the last version are returned.
 * @return A sorted {@code List} containing {@link ReleaseItem}s representing the (partial)
 * change log.
 * @see #getChangeLogComparator()
 */
public List<ReleaseItem> getChangeLog(boolean full) {
    SparseArray<ReleaseItem> masterChangelog = getMasterChangeLog(full);
    SparseArray<ReleaseItem> changelog = getLocalizedChangeLog(full);

    List<ReleaseItem> mergedChangeLog = new ArrayList<>(masterChangelog.size());

    for (int i = 0, len = masterChangelog.size(); i < len; i++) {
        int key = masterChangelog.keyAt(i);

        // Use release information from localized change log and fall back to the master file
        // if necessary.
        ReleaseItem release = changelog.get(key, masterChangelog.get(key));

        mergedChangeLog.add(release);
    }

    Collections.sort(mergedChangeLog, getChangeLogComparator());

    return mergedChangeLog;
}

From source file:com.linroid.pushapp.service.ApkAutoInstallService.java

/**
 * ?AccessibilityNodeInfo//  w  w  w.  j  a v  a2 s. c  o  m
 *
 * @param event
 * @param validPackageList 
 * @return
 */
private AccessibilityNodeInfo getValidAccessibilityNodeInfo(AccessibilityEvent event,
        SparseArray<Pack> validPackageList) {
    if (validPackageList != null && validPackageList.size() > 0) {
        for (int i = 0; i < validPackageList.size(); i++) {
            int key = validPackageList.keyAt(i);
            Pack pack = validPackageList.get(key);
            AccessibilityNodeInfo nodeInfo = getAccessibilityNodeInfoByText(event, pack.getAppName());
            if (nodeInfo != null) {
                return nodeInfo;
            }
        }
    }
    return null;
}