androidx.collection.LongSparseArray Java Examples

The following examples show how to use androidx.collection.LongSparseArray. 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: DiffPayload.java    From epoxy with Apache License 2.0 6 votes vote down vote up
DiffPayload(List<? extends EpoxyModel<?>> models) {
  if (models.isEmpty()) {
    throw new IllegalStateException("Models must not be empty");
  }

  int modelCount = models.size();

  if (modelCount == 1) {
    // Optimize for the common case of only one model changed.
    singleModel = models.get(0);
    modelsById = null;
  } else {
    singleModel = null;
    modelsById = new LongSparseArray<>(modelCount);
    for (EpoxyModel<?> model : models) {
      modelsById.put(model.id(), model);
    }
  }
}
 
Example #2
Source File: Profile.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
private String getValuesList(LongSparseArray<Double> array, LongSparseArray<Double> array2, DecimalFormat format, String units) {
    String retValue = "";

    for (Integer index = 0; index < array.size(); index++) {
        retValue += format_HH_MM((int) array.keyAt(index));
        retValue += "    ";
        retValue += format.format(array.valueAt(index));
        if (array2 != null) {
            retValue += " - ";
            retValue += format.format(array2.valueAt(index));
        }
        retValue += " " + units;
        if (index + 1 < array.size())
            retValue += "\n";
    }
    return retValue;
}
 
Example #3
Source File: LottieComposition.java    From lottie-android with Apache License 2.0 6 votes vote down vote up
@RestrictTo(RestrictTo.Scope.LIBRARY)
public void init(Rect bounds, float startFrame, float endFrame, float frameRate,
    List<Layer> layers, LongSparseArray<Layer> layerMap, Map<String,
    List<Layer>> precomps, Map<String, LottieImageAsset> images,
    SparseArrayCompat<FontCharacter> characters, Map<String, Font> fonts,
    List<Marker> markers) {
  this.bounds = bounds;
  this.startFrame = startFrame;
  this.endFrame = endFrame;
  this.frameRate = frameRate;
  this.layers = layers;
  this.layerMap = layerMap;
  this.precomps = precomps;
  this.images = images;
  this.characters = characters;
  this.fonts = fonts;
  this.markers = markers;
}
 
Example #4
Source File: LottieCompositionParser.java    From lottie-android with Apache License 2.0 6 votes vote down vote up
private static void parseLayers(JsonReader reader, LottieComposition composition,
                                List<Layer> layers, LongSparseArray<Layer> layerMap) throws IOException {
  int imageCount = 0;
  reader.beginArray();
  while (reader.hasNext()) {
    Layer layer = LayerParser.parse(reader, composition);
    if (layer.getLayerType() == Layer.LayerType.IMAGE) {
      imageCount++;
    }
    layers.add(layer);
    layerMap.put(layer.getId(), layer);

    if (imageCount > 4) {
      Logger.warning("You have " + imageCount + " images. Lottie should primarily be " +
          "used with shapes. If you are using Adobe Illustrator, convert the Illustrator layers" +
          " to shape layers.");
    }
  }
  reader.endArray();
}
 
Example #5
Source File: LottieCompositionMoshiParser.java    From lottie-android with Apache License 2.0 6 votes vote down vote up
private static void parseLayers(JsonReader reader, LottieComposition composition,
                                List<Layer> layers, LongSparseArray<Layer> layerMap) throws IOException {
  int imageCount = 0;
  reader.beginArray();
  while (reader.hasNext()) {
    Layer layer = LayerParser.parse(reader, composition);
    if (layer.getLayerType() == Layer.LayerType.IMAGE) {
      imageCount++;
    }
    layers.add(layer);
    layerMap.put(layer.getId(), layer);

    if (imageCount > 4) {
      Logger.warning("You have " + imageCount + " images. Lottie should primarily be " +
          "used with shapes. If you are using Adobe Illustrator, convert the Illustrator layers" +
          " to shape layers.");
    }
  }
  reader.endArray();
}
 
Example #6
Source File: ThreadRegistry.java    From mimi-reader with Apache License 2.0 6 votes vote down vote up
public void init() {
    if (threadArray != null) {
        threadArray.clear();
    } else {
        threadArray = new LongSparseArray<>();
    }

    Disposable sub = HistoryTableConnection.fetchHistory(true, 0, false)
            .compose(DatabaseUtils.applySingleSchedulers())
            .subscribe(historyList -> {
                for (History historyDbModel : historyList) {
                    final ThreadRegistryModel t = new ThreadRegistryModel(historyDbModel, Collections.emptyList());
                    final long i = historyDbModel.threadId;

                    Log.d(LOG_TAG, "[refresh] Adding bookmark to registry: size=" + historyDbModel.threadSize);

                    threadArray.append(i, t);
                }
            });
}
 
Example #7
Source File: SkinCompatDrawableManager.java    From Android-skin-support with MIT License 6 votes vote down vote up
private boolean addDrawableToCache(@NonNull final Context context, final long key,
                                   @NonNull final Drawable drawable) {
    final ConstantState cs = drawable.getConstantState();
    if (cs != null) {
        synchronized (mDrawableCacheLock) {
            LongSparseArray<WeakReference<ConstantState>> cache = mDrawableCaches.get(context);
            if (cache == null) {
                cache = new LongSparseArray<>();
                mDrawableCaches.put(context, cache);
            }
            cache.put(key, new WeakReference<ConstantState>(cs));
        }
        return true;
    }
    return false;
}
 
Example #8
Source File: SkinCompatDrawableManager.java    From Android-skin-support with MIT License 6 votes vote down vote up
private Drawable getCachedDrawable(@NonNull final Context context, final long key) {
    synchronized (mDrawableCacheLock) {
        final LongSparseArray<WeakReference<ConstantState>> cache
                = mDrawableCaches.get(context);
        if (cache == null) {
            return null;
        }

        final WeakReference<ConstantState> wr = cache.get(key);
        if (wr != null) {
            // We have the key, and the secret
            ConstantState entry = wr.get();
            if (entry != null) {
                return entry.newDrawable(context.getResources());
            } else {
                // Our entry has been purged
                cache.delete(key);
            }
        }
    }
    return null;
}
 
Example #9
Source File: GridBasedAlgorithm.java    From android-maps-utils with Apache License 2.0 6 votes vote down vote up
@Override
public Set<? extends Cluster<T>> getClusters(float zoom) {
    long numCells = (long) Math.ceil(256 * Math.pow(2, zoom) / mGridSize);
    SphericalMercatorProjection proj = new SphericalMercatorProjection(numCells);

    HashSet<Cluster<T>> clusters = new HashSet<Cluster<T>>();
    LongSparseArray<StaticCluster<T>> sparseArray = new LongSparseArray<StaticCluster<T>>();

    synchronized (mItems) {
        for (T item : mItems) {
            Point p = proj.toPoint(item.getPosition());

            long coord = getCoord(numCells, p.x, p.y);

            StaticCluster<T> cluster = sparseArray.get(coord);
            if (cluster == null) {
                cluster = new StaticCluster<T>(proj.toLatLng(new Point(Math.floor(p.x) + .5, Math.floor(p.y) + .5)));
                sparseArray.put(coord, cluster);
                clusters.add(cluster);
            }
            cluster.add(item);
        }
    }

    return clusters;
}
 
Example #10
Source File: SampleActivity.java    From Tachyon with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Create a new calendar object set to the start of today
    day = Calendar.getInstance();
    day.set(Calendar.HOUR_OF_DAY, 0);
    day.set(Calendar.MINUTE, 0);
    day.set(Calendar.SECOND, 0);
    day.set(Calendar.MILLISECOND, 0);

    // Populate today's entry in the map with a list of example events
    allEvents = new LongSparseArray<>();
    allEvents.put(day.getTimeInMillis(), new ArrayList<>(Arrays.asList(INITIAL_EVENTS)));

    dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault());
    timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());

    setContentView(R.layout.sample_activity);

    content = findViewById(R.id.sample_content);
    dateTextView = findViewById(R.id.sample_date);
    scrollView = findViewById(R.id.sample_scroll);
    dayView = findViewById(R.id.sample_day);

    // Inflate a label view for each hour the day view will display
    Calendar hour = (Calendar) day.clone();
    List<View> hourLabelViews = new ArrayList<>();
    for (int i = dayView.getStartHour(); i <= dayView.getEndHour(); i++) {
        hour.set(Calendar.HOUR_OF_DAY, i);

        TextView hourLabelView = (TextView) getLayoutInflater().inflate(R.layout.hour_label, dayView, false);
        hourLabelView.setText(timeFormat.format(hour.getTime()));
        hourLabelViews.add(hourLabelView);
    }
    dayView.setHourLabelViews(hourLabelViews);

    onDayChange();
}
 
Example #11
Source File: SkinCompatDrawableManager.java    From Android-skin-support with MIT License 5 votes vote down vote up
public void onConfigurationChanged(@NonNull Context context) {
    synchronized (mDrawableCacheLock) {
        LongSparseArray<WeakReference<ConstantState>> cache = mDrawableCaches.get(context);
        if (cache != null) {
            // Crude, but we'll just clear the cache when the configuration changes
            cache.clear();
        }
    }
}
 
Example #12
Source File: LollipopDrawablesCompat.java    From Carbon with Apache License 2.0 5 votes vote down vote up
private static Drawable getCachedDrawable(LongSparseArray<WeakReference<Drawable.ConstantState>> cache,
                                          long key, Resources res) {
    synchronized (mAccessLock) {
        WeakReference<Drawable.ConstantState> wr = cache.get(key);
        if (wr != null) {
            Drawable.ConstantState entry = wr.get();
            if (entry != null) {
                return entry.newDrawable(res);
            } else {
                cache.delete(key);
            }
        }
    }
    return null;
}
 
Example #13
Source File: MountStateRemountTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemountSameLayoutState() {
  final TestComponent component1 = create(mContext).build();
  final TestComponent component2 = create(mContext).build();
  final TestComponent component3 = create(mContext).build();
  final TestComponent component4 = create(mContext).build();

  final LithoView lithoView =
      mountComponent(
          mContext, Column.create(mContext).child(component1).child(component2).build());

  assertThat(component1.isMounted()).isTrue();
  assertThat(component2.isMounted()).isTrue();

  mountComponent(
      mContext, lithoView, Column.create(mContext).child(component3).child(component4).build());

  assertThat(component1.isMounted()).isTrue();
  assertThat(component2.isMounted()).isTrue();
  assertThat(component3.isMounted()).isFalse();
  assertThat(component4.isMounted()).isFalse();

  final MountState mountState = getInternalState(lithoView, "mMountState");
  final LongSparseArray<MountItem> indexToItemMap =
      getInternalState(mountState, "mIndexToItemMap");

  final List<Component> components = new ArrayList<>();
  for (int i = 0; i < indexToItemMap.size(); i++) {
    components.add(getLayoutOutput(indexToItemMap.valueAt(i)).getComponent());
  }

  assertThat(containsRef(components, component1)).isFalse();
  assertThat(containsRef(components, component2)).isFalse();
  assertThat(containsRef(components, component3)).isTrue();
  assertThat(containsRef(components, component4)).isTrue();
}
 
Example #14
Source File: LollipopDrawablesCompat.java    From Carbon with Apache License 2.0 5 votes vote down vote up
private static void cacheDrawable(TypedValue value, Resources resources, Resources.Theme theme, boolean isColorDrawable, long key, Drawable drawable, LongSparseArray<WeakReference<Drawable.ConstantState>> caches) {

        Drawable.ConstantState cs = drawable.getConstantState();
        if (cs == null) {
            return;
        }

        synchronized (mAccessLock) {
            caches.put(key, new WeakReference<>(cs));
        }
    }
 
Example #15
Source File: Profile.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
private double getValueToTime(LongSparseArray<Double> array, Integer timeAsSeconds) {
    Double lastValue = null;

    for (Integer index = 0; index < array.size(); index++) {
        long tas = array.keyAt(index);
        double value = array.valueAt(index);
        if (lastValue == null) lastValue = value;
        if (timeAsSeconds < tas) {
            break;
        }
        lastValue = value;
    }
    return lastValue;
}
 
Example #16
Source File: Profile.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
private double getMultiplier(LongSparseArray<Double> array) {
    double multiplier = 1d;

    if (array == isf_v)
        multiplier = 100d / percentage;
    else if (array == ic_v)
        multiplier = 100d / percentage;
    else if (array == basal_v)
        multiplier = percentage / 100d;
    else
        log.error("Unknown array type");
    return multiplier;
}
 
Example #17
Source File: MountSpecLifecycleTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Test
public void unmountAll_unmountAllItemsExceptRoot() {
  final LifecycleTracker info_child1 = new LifecycleTracker();
  final LifecycleTracker info_child2 = new LifecycleTracker();

  final Component root =
      Column.create(mLithoViewRule.getContext())
          .child(
              MountSpecLifecycleTester.create(mLithoViewRule.getContext())
                  .intrinsicSize(new Size(800, 600))
                  .lifecycleTracker(info_child1)
                  .build())
          .child(
              MountSpecLifecycleTester.create(mLithoViewRule.getContext())
                  .intrinsicSize(new Size(800, 600))
                  .lifecycleTracker(info_child2)
                  .build())
          .build();

  mLithoViewRule.setRoot(root).attachToWindow().measure().layout();

  final MountState mountState = mLithoViewRule.getLithoView().getMountState();
  LongSparseArray<MountItem> mountedItems = mountState.getIndexToItemMap();
  assertThat(mountedItems.size()).isGreaterThan(1);

  info_child1.reset();
  info_child2.reset();
  mLithoViewRule.getLithoView().unmountAllItems();

  assertThat(mountState.getIndexToItemMap().size()).isEqualTo(1);
  assertThat(mountState.getIndexToItemMap().get(0)).isNotNull();

  assertThat(info_child1.getSteps())
      .describedAs("Should call the following lifecycle methods in the following order:")
      .containsExactly(LifecycleStep.ON_UNBIND, LifecycleStep.ON_UNMOUNT);

  assertThat(info_child2.getSteps())
      .describedAs("Should call the following lifecycle methods in the following order:")
      .containsExactly(LifecycleStep.ON_UNBIND, LifecycleStep.ON_UNMOUNT);
}
 
Example #18
Source File: Profile.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
private void validate(LongSparseArray array) {
    if (array.size() == 0) {
        isValid = false;
        return;
    }
    for (int index = 0; index < array.size(); index++) {
        if (array.valueAt(index).equals(0d)) {
            isValid = false;
            return;
        }
    }
}
 
Example #19
Source File: IobCobCalculatorPlugin.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
public void clearCache() {
    synchronized (dataLock) {
        if (L.isEnabled(L.AUTOSENS))
            log.debug("Clearing cached data.");
        iobTable = new LongSparseArray<>();
        autosensDataTable = new LongSparseArray<>();
        basalDataTable = new LongSparseArray<>();
    }
}
 
Example #20
Source File: LottieValueAnimatorUnitTest.java    From lottie-android with Apache License 2.0 5 votes vote down vote up
private LottieComposition createComposition(int startFrame, int endFrame) {
  LottieComposition composition = new LottieComposition();
  composition.init(new Rect(), startFrame, endFrame, 1000, new ArrayList<Layer>(),
          new LongSparseArray<Layer>(0), new HashMap<String, List<Layer>>(0),
          new HashMap<String, LottieImageAsset>(0), new SparseArrayCompat<FontCharacter>(0),
          new HashMap<String, Font>(0), new ArrayList<Marker>());
  return composition;
}
 
Example #21
Source File: LottieDrawableTest.java    From lottie-android with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("SameParameterValue")
private LottieComposition createComposition(int startFrame, int endFrame) {
  LottieComposition composition = new LottieComposition();
  composition.init(new Rect(), startFrame, endFrame, 1000, new ArrayList<Layer>(),
          new LongSparseArray<Layer>(0), new HashMap<String, List<Layer>>(0),
          new HashMap<String, LottieImageAsset>(0), new SparseArrayCompat<FontCharacter>(0),
          new HashMap<String, Font>(0), new ArrayList<Marker>());
  return composition;
}
 
Example #22
Source File: ProfileIntervals.java    From AndroidAPS with GNU Affero General Public License v3.0 4 votes vote down vote up
public synchronized ProfileIntervals<T> reset() {
    rawData = new LongSparseArray<>();
    return this;
}
 
Example #23
Source File: ProfileIntervals.java    From AndroidAPS with GNU Affero General Public License v3.0 4 votes vote down vote up
public ProfileIntervals () {
    rawData = new LongSparseArray<>();
}
 
Example #24
Source File: LocalPlayCountStore.java    From Jockey with Apache License 2.0 4 votes vote down vote up
public LocalPlayCountStore(Context context) {
    mContext = context;
    mCounts = new LongSparseArray<>();
}
 
Example #25
Source File: Intervals.java    From AndroidAPS with GNU Affero General Public License v3.0 4 votes vote down vote up
public Intervals() {
    rawData = new LongSparseArray<T>();
}
 
Example #26
Source File: Intervals.java    From AndroidAPS with GNU Affero General Public License v3.0 4 votes vote down vote up
public synchronized Intervals<T> reset() {
    rawData = new LongSparseArray<T>();
    return this;
}
 
Example #27
Source File: HeatmapTileProvider.java    From android-maps-utils with Apache License 2.0 4 votes vote down vote up
/**
 * Calculate a reasonable maximum intensity value to map to maximum color intensity
 *
 * @param points    Collection of LatLngs to put into buckets
 * @param bounds    Bucket boundaries
 * @param radius    radius of convolution
 * @param screenDim larger dimension of screen in pixels (for scale)
 * @return Approximate max value
 */
static double getMaxValue(Collection<WeightedLatLng> points, Bounds bounds, int radius,
                          int screenDim) {
    // Approximate scale as if entire heatmap is on the screen
    // ie scale dimensions to larger of width or height (screenDim)
    double minX = bounds.minX;
    double maxX = bounds.maxX;
    double minY = bounds.minY;
    double maxY = bounds.maxY;
    double boundsDim = (maxX - minX > maxY - minY) ? maxX - minX : maxY - minY;

    // Number of buckets: have diameter sized buckets
    int nBuckets = (int) (screenDim / (2 * radius) + 0.5);
    // Scaling factor to convert width in terms of point distance, to which bucket
    double scale = nBuckets / boundsDim;

    // Make buckets
    // Use a sparse array - use LongSparseArray just in case
    LongSparseArray<LongSparseArray<Double>> buckets = new LongSparseArray<LongSparseArray<Double>>();
    //double[][] buckets = new double[nBuckets][nBuckets];

    // Assign into buckets + find max value as we go along
    double x, y;
    double max = 0;
    for (WeightedLatLng l : points) {
        x = l.getPoint().x;
        y = l.getPoint().y;

        int xBucket = (int) ((x - minX) * scale);
        int yBucket = (int) ((y - minY) * scale);

        // Check if x bucket exists, if not make it
        LongSparseArray<Double> column = buckets.get(xBucket);
        if (column == null) {
            column = new LongSparseArray<Double>();
            buckets.put(xBucket, column);
        }
        // Check if there is already a y value there
        Double value = column.get(yBucket);
        if (value == null) {
            value = 0.0;
        }
        value += l.getIntensity();
        // Yes, do need to update it, despite it being a Double.
        column.put(yBucket, value);

        if (value > max) max = value;
    }

    return max;
}
 
Example #28
Source File: IobCobCalculatorPlugin.java    From AndroidAPS with GNU Affero General Public License v3.0 4 votes vote down vote up
public LongSparseArray<AutosensData> getAutosensDataTable() {
    return autosensDataTable;
}
 
Example #29
Source File: CompositionLayer.java    From lottie-android with Apache License 2.0 4 votes vote down vote up
public CompositionLayer(LottieDrawable lottieDrawable, Layer layerModel, List<Layer> layerModels,
    LottieComposition composition) {
  super(lottieDrawable, layerModel);

  AnimatableFloatValue timeRemapping = layerModel.getTimeRemapping();
  if (timeRemapping != null) {
    this.timeRemapping = timeRemapping.createAnimation();
    addAnimation(this.timeRemapping);
    //noinspection ConstantConditions
    this.timeRemapping.addUpdateListener(this);
  } else {
    this.timeRemapping = null;
  }

  LongSparseArray<BaseLayer> layerMap =
      new LongSparseArray<>(composition.getLayers().size());

  BaseLayer mattedLayer = null;
  for (int i = layerModels.size() - 1; i >= 0; i--) {
    Layer lm = layerModels.get(i);
    BaseLayer layer = BaseLayer.forModel(lm, lottieDrawable, composition);
    if (layer == null) {
      continue;
    }
    layerMap.put(layer.getLayerModel().getId(), layer);
    if (mattedLayer != null) {
      mattedLayer.setMatteLayer(layer);
      mattedLayer = null;
    } else {
      layers.add(0, layer);
      switch (lm.getMatteType()) {
        case ADD:
        case INVERT:
          mattedLayer = layer;
          break;
      }
    }
  }

  for (int i = 0; i < layerMap.size(); i++) {
    long key = layerMap.keyAt(i);
    BaseLayer layerView = layerMap.get(key);
    // This shouldn't happen but it appears as if sometimes on pre-lollipop devices when
    // compiled with d8, layerView is null sometimes.
    // https://github.com/airbnb/lottie-android/issues/524
    if (layerView == null) {
      continue;
    }
    BaseLayer parentLayer = layerMap.get(layerView.getLayerModel().getParentId());
    if (parentLayer != null) {
      layerView.setParentLayer(parentLayer);
    }
  }
}
 
Example #30
Source File: LottieCompositionParser.java    From lottie-android with Apache License 2.0 4 votes vote down vote up
public static LottieComposition parse(JsonReader reader) throws IOException {
  float scale = Utils.dpScale();
  float startFrame = 0f;
  float endFrame = 0f;
  float frameRate = 0f;
  final LongSparseArray<Layer> layerMap = new LongSparseArray<>();
  final List<Layer> layers = new ArrayList<>();
  int width = 0;
  int height = 0;
  Map<String, List<Layer>> precomps = new HashMap<>();
  Map<String, LottieImageAsset> images = new HashMap<>();
  Map<String, Font> fonts = new HashMap<>();
  List<Marker> markers = new ArrayList<>();
  SparseArrayCompat<FontCharacter> characters = new SparseArrayCompat<>();

  LottieComposition composition = new LottieComposition();
  reader.beginObject();
  while (reader.hasNext()) {
    switch (reader.selectName(NAMES)) {
      case 0:
        width = reader.nextInt();
        break;
      case 1:
        height = reader.nextInt();
        break;
      case 2:
        startFrame = (float) reader.nextDouble();
        break;
      case 3:
        endFrame = (float) reader.nextDouble() - 0.01f;
        break;
      case 4:
        frameRate = (float) reader.nextDouble();
        break;
      case 5:
        String version = reader.nextString();
        String[] versions = version.split("\\.");
        int majorVersion = Integer.parseInt(versions[0]);
        int minorVersion = Integer.parseInt(versions[1]);
        int patchVersion = Integer.parseInt(versions[2]);
        if (!Utils.isAtLeastVersion(majorVersion, minorVersion, patchVersion,
            4, 4, 0)) {
          composition.addWarning("Lottie only supports bodymovin >= 4.4.0");
        }
        break;
      case 6:
        parseLayers(reader, composition, layers, layerMap);
      default:
        reader.skipValue();

    }
  }
  int scaledWidth = (int) (width * scale);
  int scaledHeight = (int) (height * scale);
  Rect bounds = new Rect(0, 0, scaledWidth, scaledHeight);

  composition.init(bounds, startFrame, endFrame, frameRate, layers, layerMap, precomps,
      images, characters, fonts, markers);

  return composition;
}