Java Code Examples for android.util.SparseArray#keyAt()

The following examples show how to use android.util.SparseArray#keyAt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MediaPlayer.java    From dttv-android with GNU General Public License v3.0 6 votes vote down vote up
private TrackInfo[] getInbandTrackInfo(String encoding) {
    if (mInbandTracks == null) {
        SparseArray<byte[]> trackSparse = new SparseArray<byte[]>();
        if (!native_getTrackInfo(trackSparse)) {
            return null;
        }

        int size = trackSparse.size();
        mInbandTracks = new TrackInfo[size];
        for (int i = 0; i < size; i++) {
            SparseArray<app.dttv.dttvlib.MediaFormat> sparseArray = parseTrackInfo(trackSparse.valueAt(i), encoding);
            TrackInfo trackInfo = new TrackInfo(trackSparse.keyAt(i), sparseArray);
            mInbandTracks[i] = trackInfo;
        }
    }
    return mInbandTracks;
}
 
Example 2
Source File: ChangeLog.java    From ckChangeLog with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the merged change log.
 *
 * @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<ReleaseItem>(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;
}
 
Example 3
Source File: MediaPlayer.java    From Vitamio with Apache License 2.0 6 votes vote down vote up
private TrackInfo[] getInbandTrackInfo(String encoding) {
	if (mInbandTracks == null) {
		SparseArray<byte[]> trackSparse = new SparseArray<byte[]>();
    if (!native_getTrackInfo(trackSparse)) {
      return null;
    }

    int size = trackSparse.size();
    mInbandTracks = new TrackInfo[size];
    for (int i = 0; i < size; i++) {
    	SparseArray<MediaFormat> sparseArray = parseTrackInfo(trackSparse.valueAt(i), encoding);
      TrackInfo trackInfo = new TrackInfo(trackSparse.keyAt(i), sparseArray);
      mInbandTracks[i] = trackInfo;
    }
	}
  return mInbandTracks;
}
 
Example 4
Source File: AlarmManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
        SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
        Predicate<Alarm> isBackgroundRestricted) {

    for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
        final int uid = pendingAlarms.keyAt(uidIndex);
        final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);

        for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
            final Alarm alarm = alarmsForUid.get(alarmIndex);

            if (isBackgroundRestricted.test(alarm)) {
                continue;
            }

            unrestrictedAlarms.add(alarm);
            alarmsForUid.remove(alarmIndex);
        }

        if (alarmsForUid.size() == 0) {
            pendingAlarms.removeAt(uidIndex);
        }
    }
}
 
Example 5
Source File: CPUFragment.java    From MTweaks-KernelAdiutorMOD with GNU General Public License v3.0 6 votes vote down vote up
private void refreshCores(SparseArray<SwitchView> array, int[] freqs) {
    for (int i = 0; i < array.size(); i++) {
        SwitchView switchView = array.valueAt(i);
        if (switchView != null) {
            final int core = array.keyAt(i);
            int freq = freqs[core];

            String freqText = freq == 0 ? getString(R.string.offline) : (freq / 1000)
                    + getString(R.string.mhz);
            switchView.clearOnSwitchListener();
            switchView.setChecked(freq != 0);
            switchView.setSummary(getString(R.string.core, core + 1) + " - " + freqText);
            switchView.addOnSwitchListener((switchView1, isChecked) -> {
                if (core == 0) {
                    Utils.toast(R.string.no_offline_core, getActivity());
                } else {
                    mCPUFreq.onlineCpu(core, isChecked, true, getActivity());
                }
            });
        }
    }
}
 
Example 6
Source File: RecycleBin.java    From SprintNBA with Apache License 2.0 6 votes vote down vote up
static View retrieveFromScrap(SparseArray<View> scrapViews, int position) {
	int size = scrapViews.size();
	if (size > 0) {
		// See if we still have a view for this position.
		for (int i = 0; i < size; i++) {
			int fromPosition = scrapViews.keyAt(i);
			View view = scrapViews.get(fromPosition);
			if (fromPosition == position) {
				scrapViews.remove(fromPosition);
				return view;
			}
		}
		int index = size - 1;
		View r = scrapViews.valueAt(index);
		scrapViews.remove(scrapViews.keyAt(index));
		return r;
	} else {
		return null;
	}
}
 
Example 7
Source File: ViewData.java    From TabStacker with Apache License 2.0 6 votes vote down vote up
static Bundle saveViewHierarchy(@NonNull View view) {

        Bundle bundle = new Bundle();
        SparseArray<Parcelable> savedViewHierarchy = new SparseArray<>();

        view.saveHierarchyState(savedViewHierarchy);

        int count = savedViewHierarchy.size();
        for(int i=0; i<count; ++i) {
            int key = savedViewHierarchy.keyAt(i);
            Parcelable parcelable = savedViewHierarchy.get(key);
            String bundleKey = "" + key;
            bundle.putParcelable(bundleKey, parcelable);
        }

        return bundle;
    }
 
Example 8
Source File: DocumentProcessor.java    From CVScanner with GNU General Public License v3.0 6 votes vote down vote up
@Override
public int selectFocus(Detector.Detections<Document> detections) {
    SparseArray<Document> detectedItems;
    if((detectedItems = detections.getDetectedItems()).size() == 0) {
        throw new IllegalArgumentException("No documents for selectFocus.");
    } else {
        int itemKey = detectedItems.keyAt(0);
        int itemArea = detectedItems.valueAt(0).getMaxArea();

        for(int index = 1; index < detectedItems.size(); ++index) {
            int itemKey2 = detectedItems.keyAt(index);
            int itemArea2;
            if((itemArea2 = detectedItems.valueAt(index).getMaxArea()) > itemArea) {
                itemKey = itemKey2;
                itemArea = itemArea2;
            }
        }

        return itemKey;
    }
}
 
Example 9
Source File: ObjectIdMapper.java    From Dream-Catcher with MIT License 5 votes vote down vote up
public void clear() {
  SparseArray<Object> idToObjectMap;
  synchronized (mSync) {
    idToObjectMap = mIdToObjectMap;
    mObjectToIdMap.clear();
    mIdToObjectMap = new SparseArray<Object>();
  }

  int size = idToObjectMap.size();
  for (int i = 0; i < size; ++i) {
    int id = idToObjectMap.keyAt(i);
    Object object = idToObjectMap.valueAt(i);
    onUnmapped(object, id);
  }
}
 
Example 10
Source File: ResultsActivity.java    From Onesearch with MIT License 5 votes vote down vote up
private void updateAchievements() {
    int score = Math.max(mPreviousBestScore, mScore);
    SparseArray<String> achievementsMap = null;
    switch (mGameMode.getDifficulty()) {
        case GameDifficulty.Easy:
            achievementsMap = GameAchievement.EASYACHIEVEMENTSMAP;
            break;
        case GameDifficulty.Medium:
            achievementsMap = GameAchievement.MEDIUMACHIEVEMENTSMAP;
            break;
        case GameDifficulty.Hard:
            achievementsMap = GameAchievement.HARDACHIEVEMENTSMAP;
            break;
        case GameDifficulty.Advanced:
            achievementsMap = GameAchievement.ADVANCEDACHIEVEMENTSMAP;
            break;
    }
    if (achievementsMap == null) return;
    // Remember the highest score associated with achievement unlocked, so we don't unlock it multiple times
    SharedPreferences prefs = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
    int highestScore = prefs.getInt(HIGHEST_SCORE_FOR_ACHIEVEMENT_PREFIX + mGameMode.getDifficulty(), 0);

    for (int i = 0; i < achievementsMap.size(); i++) {
        int key = achievementsMap.keyAt(i);
        if (key > score) break;
        if (key <= highestScore) continue;
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
            Games.Achievements.unlock(mGoogleApiClient, achievementsMap.get(key, ""));
    }

    if (score > highestScore) {
        SharedPreferences.Editor editor = getSharedPreferences(PREF_NAME, MODE_PRIVATE).edit();
        editor.putInt(HIGHEST_SCORE_FOR_ACHIEVEMENT_PREFIX + mGameMode.getDifficulty(), score);
        editor.apply();
    }
}
 
Example 11
Source File: AnkiDroidHelper.java    From ankihelper with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Remove the duplicates from a list of note fields and tags
 *
 * @param fields  List of fields to remove duplicates from
 * @param tags    List of tags to remove duplicates from
 * @param modelId ID of model to search for duplicates on
 */
public void removeDuplicates(LinkedList<String[]> fields, LinkedList<Set<String>> tags, long modelId) {
    // Build a list of the duplicate keys (first fields) and find all notes that have a match with each key
    List<String> keys = new ArrayList<>(fields.size());
    for (String[] f : fields) {
        keys.add(f[0]);
    }
    SparseArray<List<NoteInfo>> duplicateNotes = getApi().findDuplicateNotes(modelId, keys);
    // Do some sanity checks
    if (tags.size() != fields.size()) {
        throw new IllegalStateException("List of tags must be the same length as the list of fields");
    }
    if (duplicateNotes.size() == 0 || fields.size() == 0 || tags.size() == 0) {
        return;
    }
    if (duplicateNotes.keyAt(duplicateNotes.size() - 1) >= fields.size()) {
        throw new IllegalStateException("The array of duplicates goes outside the bounds of the original lists");
    }
    // Iterate through the fields and tags LinkedLists, removing those that had a duplicate
    ListIterator<String[]> fieldIterator = fields.listIterator();
    ListIterator<Set<String>> tagIterator = tags.listIterator();
    int listIndex = -1;
    for (int i = 0; i < duplicateNotes.size(); i++) {
        int duplicateIndex = duplicateNotes.keyAt(i);
        while (listIndex < duplicateIndex) {
            fieldIterator.next();
            tagIterator.next();
            listIndex++;
        }
        fieldIterator.remove();
        tagIterator.remove();
    }
}
 
Example 12
Source File: BarcodeCentralFocusingProcessor.java    From google-authenticator-android with Apache License 2.0 5 votes vote down vote up
/**
 * We only accept the barcode inside the scanner square. Note that the return dimensions for the
 * barcodes is based on the camera's coordinates, so we must convert it to the canvas' coordinate
 * for comparing with the scanner square.
 */
@Override
public int selectFocus(Detections<Barcode> detections) {
  SparseArray<Barcode> barcodes = detections.getDetectedItems();
  for (int i = 0; i < barcodes.size(); ++i) {
    int id = barcodes.keyAt(i);
    if (!mCentralFilterEnabled
        || BarcodeCentralFilter.barcodeIsInsideScannerSquare(barcodes.valueAt(i))) {
      return id;
    }
  }
  return -1;
}
 
Example 13
Source File: PriorityBlockingAggregatorQueue.java    From tilt-game-android with MIT License 5 votes vote down vote up
@Override
public String toString() {
	final ReentrantLock lock = this.mLock;
	lock.lock();

	try {
		final StringBuilder stringBuilder = new StringBuilder();

		if (this.mQueues.size() > 0) {
			final SparseArray<IList<T>> queues = this.mQueues;
			final SparseIntArray queueCapacities = this.mQueueCapacities;

			stringBuilder.append(" [\n");

			final int queueCount = queues.size();
			for (int i = 0; i < queueCount; i++) {
				final int priority = queues.keyAt(i);
				final IList<T> queue = queues.valueAt(i);
				final int queueCapacity = queueCapacities.valueAt(i);
				final int queueSize = queue.size();

				stringBuilder.append("\tPriority: ").append(priority).append(" (Capacity: ").append(queueSize).append('/').append(queueCapacity).append("): ");
				stringBuilder.append(queue.toString());

				if (i < (queueCount - 1)) {
					stringBuilder.append(',');
				}
				stringBuilder.append('\n');
			}

			stringBuilder.append(']');
		}

		return stringBuilder.toString();
	} finally {
		lock.unlock();
	}
}
 
Example 14
Source File: Node.java    From BlueSTSDK_Android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public boolean isExportingFeature(Class<? extends Feature> featureClass) {
    SparseArray<Class<? extends Feature>> decoder = Manager.getNodeFeatures(
            getTypeId());
    long advertiseBitMask = getAdvertiseBitMask();
    for (int i = 0 ; i< decoder.size(); i++){
        if(featureClass == decoder.valueAt(i)){
            long mask = decoder.keyAt(i);
            if((advertiseBitMask & mask) != 0)
                return true;
        }
    }
    return false;
}
 
Example 15
Source File: CachedContentIndex.java    From K-Sonic with MIT License 5 votes vote down vote up
/**
 * Returns an id which isn't used in the given array. If the maximum id in the array is smaller
 * than {@link java.lang.Integer#MAX_VALUE} it just returns the next bigger integer. Otherwise it
 * returns the smallest unused non-negative integer.
 */
//@VisibleForTesting
public static int getNewId(SparseArray<String> idToKey) {
  int size = idToKey.size();
  int id = size == 0 ? 0 : (idToKey.keyAt(size - 1) + 1);
  if (id < 0) { // In case if we pass max int value.
    // TODO optimization: defragmentation or binary search?
    for (id = 0; id < size; id++) {
      if (id != idToKey.keyAt(id)) {
        break;
      }
    }
  }
  return id;
}
 
Example 16
Source File: MessageHolders.java    From ChatKit with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected void bind(final ViewHolder holder, final Object item, boolean isSelected,
                    final ImageLoader imageLoader,
                    final View.OnClickListener onMessageClickListener,
                    final View.OnLongClickListener onMessageLongClickListener,
                    final DateFormatter.Formatter dateHeadersFormatter,
                    final SparseArray<MessagesListAdapter.OnMessageViewClickListener> clickListenersArray) {

    if (item instanceof IMessage) {
        ((MessageHolders.BaseMessageViewHolder) holder).isSelected = isSelected;
        ((MessageHolders.BaseMessageViewHolder) holder).imageLoader = imageLoader;
        holder.itemView.setOnLongClickListener(onMessageLongClickListener);
        holder.itemView.setOnClickListener(onMessageClickListener);

        for (int i = 0; i < clickListenersArray.size(); i++) {
            final int key = clickListenersArray.keyAt(i);
            final View view = holder.itemView.findViewById(key);
            if (view != null) {
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        clickListenersArray.get(key).onMessageViewClick(view, (IMessage) item);
                    }
                });
            }
        }
    } else if (item instanceof Date) {
        ((MessageHolders.DefaultDateHeaderViewHolder) holder).dateHeadersFormatter = dateHeadersFormatter;
    }

    holder.onBind(item);
}
 
Example 17
Source File: MainWindow.java    From NetCloud_android with GNU General Public License v2.0 5 votes vote down vote up
private void initData(){
    SparseArray<List<ConnInfo>> uid2Conns = TrafficMgr.getInstance().getConnsCategoryByUid();

    if(uid2Conns != null){
        for(int i=0;i<uid2Conns.size();i++){
            int uid = uid2Conns.keyAt(i);
            List<ConnInfo> conns = uid2Conns.get(uid);
            AppConnInfo appConn = new AppConnInfo();
            appConn.uid = uid;
            appConn.connNum = TrafficMgr.getInstance().getConnNum(uid);

            if(conns != null && !conns.isEmpty()){
                for(ConnInfo conn:conns){
                    appConn.accept += conn.accept;
                    appConn.back += conn.back;
                    appConn.sent += conn.sent;
                    appConn.recv += conn.recv;

                    if(conn.alive){
                        ++appConn.alive;
                    }
                }
            }

            mUID2AppInfo.put(uid, appConn);
            getData().add(uid);
        }
    }
}
 
Example 18
Source File: YouTubeExtractor.java    From YouTube-In-Background with MIT License 4 votes vote down vote up
private void decipherViaWebView(final SparseArray<String> encSignatures)
{
    final Context context = weakContext.get();
    if (context == null) {
        return;
    }

    final StringBuilder stb = new StringBuilder(decipherFunctions + " function decipher(");
    stb.append("){return ");

    for (int i = 0; i < encSignatures.size(); i++) {
        int key = encSignatures.keyAt(i);
        if (i < encSignatures.size() - 1) {
            stb.append(decipherFunctionName)
                    .append("('")
                    .append(encSignatures.get(key))
                    .append("')+\"\\n\"+");
        } else {
            stb.append(decipherFunctionName)
                    .append("('")
                    .append(encSignatures.get(key))
                    .append("')");
        }
    }
    stb.append("};decipher();");


    if (LOGGING) Log.e(LOG_TAG, "FunctionDecipher: " + stb);

    new Handler(Looper.getMainLooper()).post(() -> new JsEvaluator(context).evaluate(stb.toString(), new JsCallback()
    {
        @Override
        public void onResult(String result)
        {
            lock.lock();
            try {
                decipheredSignature = result;

                if (LOGGING) Log.e(LOG_TAG, "JsEvaluator-result: " + result);
                jsExecuting.signal();
            } finally {
                lock.unlock();
            }
        }

        @Override
        public void onError(String errorMessage)
        {
            lock.lock();
            try {
                if (LOGGING)
                    Log.e(LOG_TAG, errorMessage);
                jsExecuting.signal();
            } finally {
                lock.unlock();
            }
        }
    }));
}
 
Example 19
Source File: Node.java    From BlueSTSDK_Android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private int extractFeatureMask(Feature f){
    SparseArray<Class<? extends Feature>> decoder = Manager.getNodeFeatures(
            mAdvertise.getDeviceId());
    int index = decoder.indexOfValue(f.getClass());
    return decoder.keyAt(index);
}
 
Example 20
Source File: DvbParser.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Decodes a subtitling packet, returning a list of parsed {@link Cue}s.
 *
 * @param data The subtitling packet data to decode.
 * @param limit The limit in {@code data} at which to stop decoding.
 * @return The parsed {@link Cue}s.
 */
public List<Cue> decode(byte[] data, int limit) {
  // Parse the input data.
  ParsableBitArray dataBitArray = new ParsableBitArray(data, limit);
  while (dataBitArray.bitsLeft() >= 48 // sync_byte (8) + segment header (40)
      && dataBitArray.readBits(8) == 0x0F) {
    parseSubtitlingSegment(dataBitArray, subtitleService);
  }

  if (subtitleService.pageComposition == null) {
    return Collections.emptyList();
  }

  // Update the canvas bitmap if necessary.
  DisplayDefinition displayDefinition = subtitleService.displayDefinition != null
      ? subtitleService.displayDefinition : defaultDisplayDefinition;
  if (bitmap == null || displayDefinition.width + 1 != bitmap.getWidth()
      || displayDefinition.height + 1 != bitmap.getHeight()) {
    bitmap = Bitmap.createBitmap(displayDefinition.width + 1, displayDefinition.height + 1,
        Bitmap.Config.ARGB_8888);
    canvas.setBitmap(bitmap);
  }

  // Build the cues.
  List<Cue> cues = new ArrayList<>();
  SparseArray<PageRegion> pageRegions = subtitleService.pageComposition.regions;
  for (int i = 0; i < pageRegions.size(); i++) {
    PageRegion pageRegion = pageRegions.valueAt(i);
    int regionId = pageRegions.keyAt(i);
    RegionComposition regionComposition = subtitleService.regions.get(regionId);

    // Clip drawing to the current region and display definition window.
    int baseHorizontalAddress = pageRegion.horizontalAddress
        + displayDefinition.horizontalPositionMinimum;
    int baseVerticalAddress = pageRegion.verticalAddress
        + displayDefinition.verticalPositionMinimum;
    int clipRight = Math.min(baseHorizontalAddress + regionComposition.width,
        displayDefinition.horizontalPositionMaximum);
    int clipBottom = Math.min(baseVerticalAddress + regionComposition.height,
        displayDefinition.verticalPositionMaximum);
    canvas.clipRect(baseHorizontalAddress, baseVerticalAddress, clipRight, clipBottom,
        Region.Op.REPLACE);

    ClutDefinition clutDefinition = subtitleService.cluts.get(regionComposition.clutId);
    if (clutDefinition == null) {
      clutDefinition = subtitleService.ancillaryCluts.get(regionComposition.clutId);
      if (clutDefinition == null) {
        clutDefinition = defaultClutDefinition;
      }
    }

    SparseArray<RegionObject> regionObjects = regionComposition.regionObjects;
    for (int j = 0; j < regionObjects.size(); j++) {
      int objectId = regionObjects.keyAt(j);
      RegionObject regionObject = regionObjects.valueAt(j);
      ObjectData objectData = subtitleService.objects.get(objectId);
      if (objectData == null) {
        objectData = subtitleService.ancillaryObjects.get(objectId);
      }
      if (objectData != null) {
        Paint paint = objectData.nonModifyingColorFlag ? null : defaultPaint;
        paintPixelDataSubBlocks(objectData, clutDefinition, regionComposition.depth,
            baseHorizontalAddress + regionObject.horizontalPosition,
            baseVerticalAddress + regionObject.verticalPosition, paint, canvas);
      }
    }

    if (regionComposition.fillFlag) {
      int color;
      if (regionComposition.depth == REGION_DEPTH_8_BIT) {
        color = clutDefinition.clutEntries8Bit[regionComposition.pixelCode8Bit];
      } else if (regionComposition.depth == REGION_DEPTH_4_BIT) {
        color = clutDefinition.clutEntries4Bit[regionComposition.pixelCode4Bit];
      } else {
        color = clutDefinition.clutEntries2Bit[regionComposition.pixelCode2Bit];
      }
      fillRegionPaint.setColor(color);
      canvas.drawRect(baseHorizontalAddress, baseVerticalAddress,
          baseHorizontalAddress + regionComposition.width,
          baseVerticalAddress + regionComposition.height,
          fillRegionPaint);
    }

    Bitmap cueBitmap = Bitmap.createBitmap(bitmap, baseHorizontalAddress, baseVerticalAddress,
        regionComposition.width, regionComposition.height);
    cues.add(new Cue(cueBitmap, (float) baseHorizontalAddress / displayDefinition.width,
        Cue.ANCHOR_TYPE_START, (float) baseVerticalAddress / displayDefinition.height,
        Cue.ANCHOR_TYPE_START, (float) regionComposition.width / displayDefinition.width,
        (float) regionComposition.height / displayDefinition.height));

    canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
  }

  return cues;
}