Java Code Examples for android.util.SparseIntArray#size()

The following examples show how to use android.util.SparseIntArray#size() . 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: BasePool.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize the list of buckets. Get the bucket sizes (and bucket lengths) from the bucket
 * sizes provider
 * @param inUseCounts map of current buckets and their in use counts
 */
private synchronized void initBuckets(SparseIntArray inUseCounts) {
  Preconditions.checkNotNull(inUseCounts);

  // clear out all the buckets
  mBuckets.clear();

  // create the new buckets
  final SparseIntArray bucketSizes = mPoolParams.bucketSizes;
  if (bucketSizes != null) {
    for (int i = 0; i < bucketSizes.size(); ++i) {
      final int bucketSize = bucketSizes.keyAt(i);
      final int maxLength = bucketSizes.valueAt(i);
      int bucketInUseCount = inUseCounts.get(bucketSize, 0);
      mBuckets.put(
          bucketSize,
          new Bucket<V>(
              getSizeInBytes(bucketSize),
              maxLength,
              bucketInUseCount));
    }
    mAllowNewBuckets = false;
  } else {
    mAllowNewBuckets = true;
  }
}
 
Example 2
Source File: KeyMapper.java    From J2ME-Loader with Apache License 2.0 6 votes vote down vote up
public static void saveArrayPref(SharedPreferencesContainer container, SparseIntArray intArray) {
	JSONArray json = new JSONArray();
	StringBuilder  data = new StringBuilder().append("[");
	for (int i = 0; i < intArray.size(); i++) {
		data.append("{")
				.append("\"key\": ")
				.append(intArray.keyAt(i)).append(",")
				.append("\"value\": ")
				.append(intArray.valueAt(i))
				.append("},");
		json.put(data);
	}
	data.deleteCharAt(data.length() - 1);
	data.append("]");
	container.putString(PREF_KEY, intArray.size() == 0 ? null : data.toString());
	container.apply();
}
 
Example 3
Source File: NetworkManagementService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void syncFirewallChainLocked(int chain, String name) {
    SparseIntArray rules;
    synchronized (mRulesLock) {
        final SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
        // Make a copy of the current rules, and then clear them. This is because
        // setFirewallUidRuleInternal only pushes down rules to the native daemon if they
        // are different from the current rules stored in the mUidFirewall*Rules array for
        // the specified chain. If we don't clear the rules, setFirewallUidRuleInternal
        // will do nothing.
        rules = uidFirewallRules.clone();
        uidFirewallRules.clear();
    }
    if (rules.size() > 0) {
        // Now push the rules. setFirewallUidRuleInternal will push each of these down to the
        // native daemon, and also add them to the mUidFirewall*Rules array for the specified
        // chain.
        if (DBG) Slog.d(TAG, "Pushing " + rules.size() + " active firewall "
                + name + "UID rules");
        for (int i = 0; i < rules.size(); i++) {
            setFirewallUidRuleLocked(chain, rules.keyAt(i), rules.valueAt(i));
        }
    }
}
 
Example 4
Source File: GridLayoutManager.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
static int findFirstKeyLessThan(SparseIntArray cache, int position) {
    int lo = 0;
    int hi = cache.size() - 1;

    while (lo <= hi) {
        // Using unsigned shift here to divide by two because it is guaranteed to not
        // overflow.
        final int mid = (lo + hi) >>> 1;
        final int midVal = cache.keyAt(mid);
        if (midVal < position) {
            lo = mid + 1;
        } else {
            hi = mid - 1;
        }
    }
    int index = lo - 1;
    if (index >= 0 && index < cache.size()) {
        return cache.keyAt(index);
    }
    return -1;
}
 
Example 5
Source File: AppOpsService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
    ArrayList<AppOpsManager.OpEntry> resOps = null;
    if (ops == null) {
        resOps = new ArrayList<>();
        for (int j=0; j<uidOps.size(); j++) {
            resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(j), uidOps.valueAt(j),
                    0, 0, 0, -1, null));
        }
    } else {
        for (int j=0; j<ops.length; j++) {
            int index = uidOps.indexOfKey(ops[j]);
            if (index >= 0) {
                if (resOps == null) {
                    resOps = new ArrayList<>();
                }
                resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(index), uidOps.valueAt(index),
                        0, 0, 0, -1, null));
            }
        }
    }
    return resOps;
}
 
Example 6
Source File: Binder.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Dump per uid binder proxy counts to the logcat.
 */
private void dumpPerUidProxyCounts() {
    SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts();
    if (counts.size() == 0) return;
    Log.d(Binder.TAG, "Per Uid Binder Proxy Counts:");
    for (int i = 0; i < counts.size(); i++) {
        final int uid = counts.keyAt(i);
        final int binderCount = counts.valueAt(i);
        Log.d(Binder.TAG, "UID : " + uid + "  count = " + binderCount);
    }
}
 
Example 7
Source File: ParcelUtils.java    From xdroid with Apache License 2.0 5 votes vote down vote up
public static void writeSparseIntArray(Parcel out, SparseIntArray value) {
    if (value == null) {
        out.writeInt(-1);
    } else {
        int count = value.size();
        out.writeInt(count);

        for (int i = 0; i < count; ++i) {
            out.writeInt(value.keyAt(i));
            out.writeInt(value.valueAt(i));
        }
    }
}
 
Example 8
Source File: ResourcesManager.java    From MultiTypeRecyclerViewAdapter with Apache License 2.0 5 votes vote down vote up
private void registerLevel(int level) {
    LevelManager typesManager = mLevelManagerMap.get(level);
    final SparseIntArray typeRes = typesManager.typeRes;
    final int size = typeRes.size();
    for (int i = 0; i < size; i++) {
        final int type = typeRes.keyAt(i);
        final int layoutResId = typeRes.valueAt(i);
        if (layoutResId == 0) {
            throw new RuntimeException(String.format(Locale.getDefault(), "are you sure register the layoutResId of level = %d?", type));
        }
        mLevelMap.put(type, level);
        mLayoutMap.put(type, layoutResId);
    }
    mAttrMap.put(level, new AttrEntity(typesManager.minSize, typesManager.isFolded));
    final int headerResId = typesManager.headerResId;
    if (headerResId != 0) {
        final int headerType = level - RecyclerViewAdapterHelper.HEADER_TYPE_DIFFER;
        mLevelMap.put(headerType, level);
        mLayoutMap.put(headerType, headerResId);
    }
    final int footerResId = typesManager.footerResId;
    if (footerResId != 0) {
        final int footerType = level - RecyclerViewAdapterHelper.FOOTER_TYPE_DIFFER;
        mLevelMap.put(footerType, level);
        mLayoutMap.put(footerType, footerResId);
    }
}
 
Example 9
Source File: SparseArrayUtils.java    From tilt-game-android with MIT License 5 votes vote down vote up
public static final IntArrayList valuesToList(final SparseIntArray pSparseIntArray) {
	final int size = pSparseIntArray.size();
	final IntArrayList result = new IntArrayList(size);

	for (int i = 0; i < size; i++) {
		result.add(pSparseIntArray.valueAt(i));
	}

	return result;
}
 
Example 10
Source File: BasePool.java    From fresco with MIT License 5 votes vote down vote up
/**
 * Initialize the list of buckets. Get the bucket sizes (and bucket lengths) from the bucket sizes
 * provider
 *
 * @param inUseCounts map of current buckets and their in use counts
 */
private synchronized void legacyInitBuckets(SparseIntArray inUseCounts) {
  Preconditions.checkNotNull(inUseCounts);

  // clear out all the buckets
  mBuckets.clear();

  // create the new buckets
  final SparseIntArray bucketSizes = mPoolParams.bucketSizes;
  if (bucketSizes != null) {
    for (int i = 0; i < bucketSizes.size(); ++i) {
      final int bucketSize = bucketSizes.keyAt(i);
      final int maxLength = bucketSizes.valueAt(i);
      int bucketInUseCount = inUseCounts.get(bucketSize, 0);
      mBuckets.put(
          bucketSize,
          new Bucket<V>(
              getSizeInBytes(bucketSize),
              maxLength,
              bucketInUseCount,
              mPoolParams.fixBucketsReinitialization));
    }
    mAllowNewBuckets = false;
  } else {
    mAllowNewBuckets = true;
  }
}
 
Example 11
Source File: MemoryChunkPool.java    From fresco with MIT License 5 votes vote down vote up
/**
 * Initialize a new instance of the MemoryChunkPool
 *
 * @param memoryTrimmableRegistry the memory manager to register with
 * @param poolParams provider for pool parameters
 * @param memoryChunkPoolStatsTracker the pool stats tracker
 */
MemoryChunkPool(
    MemoryTrimmableRegistry memoryTrimmableRegistry,
    PoolParams poolParams,
    PoolStatsTracker memoryChunkPoolStatsTracker) {
  super(memoryTrimmableRegistry, poolParams, memoryChunkPoolStatsTracker);
  SparseIntArray bucketSizes = poolParams.bucketSizes;
  mBucketSizes = new int[bucketSizes.size()];
  for (int i = 0; i < mBucketSizes.length; ++i) {
    mBucketSizes[i] = bucketSizes.keyAt(i);
  }
  initialize();
}
 
Example 12
Source File: NativeMemoryChunkPool.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new instance of the NativeMemoryChunkPool class
 * @param memoryTrimmableRegistry the memory manager to register with
 * @param poolParams provider for pool parameters
 * @param nativeMemoryChunkPoolStatsTracker
 */
public NativeMemoryChunkPool(
    MemoryTrimmableRegistry memoryTrimmableRegistry,
    PoolParams poolParams,
    PoolStatsTracker nativeMemoryChunkPoolStatsTracker) {
  super(memoryTrimmableRegistry, poolParams, nativeMemoryChunkPoolStatsTracker);
  SparseIntArray bucketSizes = poolParams.bucketSizes;
  mBucketSizes = new int[bucketSizes.size()];
  for (int i = 0; i < mBucketSizes.length; ++i) {
    mBucketSizes[i] = bucketSizes.keyAt(i);
  }
  initialize();
}
 
Example 13
Source File: CpuFrequencyMetrics.java    From Battery-Metrics with MIT License 5 votes vote down vote up
public @Nullable JSONObject toJSONObject() {
  if (timeInStateS.length == 0) {
    return null;
  }

  // This is slightly more complex than simply using a hashmap to aggregate frequencies
  // because SparseIntArray doesn't override equals/hash correctly.
  // Implemented in a fairly expensive, n^2 way because number of cores is presumably
  // very low.
  boolean[] isHandled = new boolean[timeInStateS.length];
  JSONObject output = new JSONObject();
  for (int i = 0, cores = timeInStateS.length; i < cores; i++) {
    SparseIntArray current = timeInStateS[i];
    if (current.size() == 0 || isHandled[i]) {
      continue;
    }

    int cpumask = 1 << i;

    for (int j = i + 1; j < cores; j++) {
      if (CpuFrequencyMetrics.sparseIntArrayEquals(current, timeInStateS[j])) {
        cpumask |= 1 << j;
        isHandled[j] = true;
      }
    }

    try {
      output.put(Integer.toHexString(cpumask), convert(current));
    } catch (JSONException je) {
      SystemMetricsLogger.wtf("CpuFrequencyMetricsReporter", "Unable to store event", je);
    }
  }

  return output;
}
 
Example 14
Source File: Parcel.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * @hide
 */
public final void writeSparseIntArray(SparseIntArray val) {
    if (val == null) {
        writeInt(-1);
        return;
    }
    int N = val.size();
    writeInt(N);
    int i=0;
    while (i < N) {
        writeInt(val.keyAt(i));
        writeInt(val.valueAt(i));
        i++;
    }
}
 
Example 15
Source File: WrapStrategy.java    From brailleback with Apache License 2.0 5 votes vote down vote up
private int findRightLimit(SparseIntArray points, int start) {
    int index = findPointIndex(points, start) + 1;
    if (index >= points.size()) {
        return mTranslation.getCells().length;
    }
    return points.keyAt(index);
}
 
Example 16
Source File: NetworkManagementService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void dumpUidFirewallRule(PrintWriter pw, String name, SparseIntArray rules) {
    pw.print("UID firewall ");
    pw.print(name);
    pw.print(" rule: [");
    final int size = rules.size();
    for (int i = 0; i < size; i++) {
        pw.print(rules.keyAt(i));
        pw.print(":");
        pw.print(rules.valueAt(i));
        if (i < size - 1) pw.print(",");
    }
    pw.println("]");
}
 
Example 17
Source File: IpConnectivityEventBuilder.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static Pair[] toPairArray(SparseIntArray counts) {
    final int s = counts.size();
    Pair[] pairs = new Pair[s];
    for (int i = 0; i < s; i++) {
        Pair p = new Pair();
        p.key = counts.keyAt(i);
        p.value = counts.valueAt(i);
        pairs[i] = p;
    }
    return pairs;
}
 
Example 18
Source File: ObjectUtils.java    From AndroidUtilCode with Apache License 2.0 4 votes vote down vote up
public static boolean isEmpty(final SparseIntArray obj) {
    return obj == null || obj.size() == 0;
}
 
Example 19
Source File: CpuFrequencyMetrics.java    From Battery-Metrics with MIT License 4 votes vote down vote up
private static void copyArrayInto(SparseIntArray source, SparseIntArray destination) {
  destination.clear();
  for (int i = 0; i < source.size(); i++) {
    destination.append(source.keyAt(i), source.valueAt(i));
  }
}
 
Example 20
Source File: TabPersistentStore.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Handles restoring an individual tab.
 *
 * @param tabToRestore Meta data about the tab to be restored.
 * @param tabState     The previously serialized state of the tab to be restored.
 * @param setAsActive  Whether the tab should be set as the active tab as part of the
 *                     restoration process.
 */
@VisibleForTesting
protected void restoreTab(
        TabRestoreDetails tabToRestore, TabState tabState, boolean setAsActive) {
    // If we don't have enough information about the Tab, bail out.
    boolean isIncognito = isIncognitoTabBeingRestored(tabToRestore, tabState);
    if (tabState == null) {
        if (tabToRestore.isIncognito == null) {
            Log.w(TAG, "Failed to restore tab: not enough info about its type was available.");
            return;
        } else if (isIncognito) {
            Log.i(TAG, "Failed to restore Incognito tab: its TabState could not be restored.");
            return;
        }
    }

    TabModel model = mTabModelSelector.getModel(isIncognito);
    SparseIntArray restoredTabs = isIncognito ? mIncognitoTabsRestored : mNormalTabsRestored;
    int restoredIndex = 0;
    if (tabToRestore.fromMerge) {
        // Put any tabs being merged into this list at the end.
        restoredIndex = mTabModelSelector.getModel(isIncognito).getCount();
    } else if (restoredTabs.size() > 0
            && tabToRestore.originalIndex > restoredTabs.keyAt(restoredTabs.size() - 1)) {
        // If the tab's index is too large, restore it at the end of the list.
        restoredIndex = restoredTabs.size();
    } else {
         // Otherwise try to find the tab we should restore before, if any.
        for (int i = 0; i < restoredTabs.size(); i++) {
            if (restoredTabs.keyAt(i) > tabToRestore.originalIndex) {
                Tab nextTabByIndex = TabModelUtils.getTabById(model, restoredTabs.valueAt(i));
                restoredIndex = nextTabByIndex != null ? model.indexOf(nextTabByIndex) : -1;
                break;
            }
        }
    }

    int tabId = tabToRestore.id;
    if (tabState != null) {
        mTabCreatorManager.getTabCreator(isIncognito).createFrozenTab(
                tabState, tabToRestore.id, restoredIndex);
    } else {
        if (NewTabPage.isNTPUrl(tabToRestore.url) && !setAsActive && !tabToRestore.fromMerge) {
            Log.i(TAG, "Skipping restore of non-selected NTP.");
            return;
        }

        Log.w(TAG, "Failed to restore TabState; creating Tab with last known URL.");
        Tab fallbackTab = mTabCreatorManager.getTabCreator(isIncognito).createNewTab(
                new LoadUrlParams(tabToRestore.url), TabModel.TabLaunchType.FROM_RESTORE, null);
        tabId = fallbackTab.getId();
        model.moveTab(tabId, restoredIndex);
    }

    // If the tab is being restored from a merge and its index is 0, then the model being
    // merged into doesn't contain any tabs. Select the first tab to avoid having no tab
    // selected. TODO(twellington): The first tab will always be selected. Instead, the tab that
    // was selected in the other model before the merge should be selected after the merge.
    if (setAsActive || (tabToRestore.fromMerge && restoredIndex == 0)) {
        boolean wasIncognitoTabModelSelected = mTabModelSelector.isIncognitoSelected();
        int selectedModelTabCount = mTabModelSelector.getCurrentModel().getCount();

        TabModelUtils.setIndex(model, TabModelUtils.getTabIndexById(model, tabId));
        boolean isIncognitoTabModelSelected = mTabModelSelector.isIncognitoSelected();

        // Setting the index will cause the tab's model to be selected. Set it back to the model
        // that was selected before setting the index if the index is being set during a merge
        // unless the previously selected model is empty (e.g. showing the empty background
        // view on tablets).
        if (tabToRestore.fromMerge
                && wasIncognitoTabModelSelected != isIncognitoTabModelSelected
                && selectedModelTabCount != 0) {
            mTabModelSelector.selectModel(wasIncognitoTabModelSelected);
        }
    }
    restoredTabs.put(tabToRestore.originalIndex, tabId);
}