Example usage for android.util SparseArray SparseArray

List of usage examples for android.util SparseArray SparseArray

Introduction

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

Prototype

public SparseArray() 

Source Link

Document

Creates a new SparseArray containing no mappings.

Usage

From source file:com.staggeredgrid.library.StaggeredGridView.java

public StaggeredGridView(final Context context, final AttributeSet attrs, final int defStyle) {
    super(context, attrs, defStyle);

    if (attrs != null) {
        // get the number of columns in portrait and landscape
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StaggeredGridView, defStyle,
                0);/*  w w  w  .  j a  v a 2  s.co m*/

        mColumnCount = typedArray.getInteger(R.styleable.StaggeredGridView_column_count, 0);

        if (mColumnCount > 0) {
            mColumnCountPortrait = mColumnCount;
            mColumnCountLandscape = mColumnCount;
        } else {
            mColumnCountPortrait = typedArray.getInteger(R.styleable.StaggeredGridView_column_count_portrait,
                    DEFAULT_COLUMNS_PORTRAIT);
            mColumnCountLandscape = typedArray.getInteger(R.styleable.StaggeredGridView_column_count_landscape,
                    DEFAULT_COLUMNS_LANDSCAPE);
        }

        mItemMargin = typedArray.getDimensionPixelSize(R.styleable.StaggeredGridView_item_margin, 0);
        mGridPaddingLeft = typedArray.getDimensionPixelSize(R.styleable.StaggeredGridView_grid_paddingLeft, 0);
        mGridPaddingRight = typedArray.getDimensionPixelSize(R.styleable.StaggeredGridView_grid_paddingRight,
                0);
        mGridPaddingTop = typedArray.getDimensionPixelSize(R.styleable.StaggeredGridView_grid_paddingTop, 0);
        mGridPaddingBottom = typedArray.getDimensionPixelSize(R.styleable.StaggeredGridView_grid_paddingBottom,
                0);

        typedArray.recycle();
    }

    mColumnCount = 0; // determined onMeasure
    // Creating these empty arrays to avoid saving null states
    mColumnTops = new int[0];
    mColumnBottoms = new int[0];
    mColumnLefts = new int[0];
    mPositionData = new SparseArray<GridItemRecord>();
}

From source file:co.lemonlabs.mortar.example.core.util.ScreenConductor.java

/**
 * Store view hierarchy state into a Screen that will be pushed into
 * the backstack of Flow//from  ww w. j a va 2 s.  com
 */
protected void storeViewState(View view, S screen) {
    if (screen != null && screen instanceof TransitionScreen) {
        SparseArray<Parcelable> state = new SparseArray<>();
        view.saveHierarchyState(state);
        ((TransitionScreen) screen).setViewState(state);
        Timber.i("Storing view state %s", state);
    }
}

From source file:tw.medfirst.com.project.baseview.CoverFlowView.java

private void init() {
    setWillNotDraw(false);/*from   w w w  .ja v  a 2  s.c o  m*/
    setClickable(true);

    mChildTransfromer = new Matrix();
    mReflectionTransfromer = new Matrix();

    mTouchRect = new RectF();
    mTouchRect2 = new ArrayList<RectF>();
    for (int i = 0; i < VISIBLE_VIEWS * 2 + 1; i++) {
        RectF r = new RectF();
        mTouchRect2.add(r);
    }

    mImageRecorder = new SparseArray<int[]>();

    mDrawChildPaint = new Paint();
    mDrawChildPaint.setAntiAlias(true);
    mDrawChildPaint.setFlags(Paint.ANTI_ALIAS_FLAG);

    mCoverFlowPadding = new Rect();

    mDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);

    mScroller = new Scroller(getContext(), new AccelerateDecelerateInterpolator());

    mRemoveReflectionPendingArray = new ArrayList<Integer>();
}

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

private void loadAllArrivals(@NonNull final List<BusStop> busStops, @NonNull final List<Station> trainStations,
        @NonNull final List<BikeStation> bikeStations) {
    final SparseArray<Map<String, List<BusArrival>>> busArrivalsMap = new SparseArray<>();
    // Execute in parallel all requests to bus arrivals
    // To be able to wait that all the threads ended we transform to list (it enforces it)
    // And then process train and bikes
    Observable.from(busStops).flatMap(
            busStop -> Observable.just(busStop).subscribeOn(Schedulers.computation()).map(currentBusStop -> {
                loadAroundBusArrivals(currentBusStop, busArrivalsMap);
                return null;
            })).doOnError(throwable -> {
                Log.e(TAG, throwable.getMessage(), throwable);
                Util.handleConnectOrParserException(throwable, null, listView, listView);
                activity.runOnUiThread(() -> showProgress(false));
            }).toList().subscribeOn(Schedulers.io()).subscribe(val -> {
                final SparseArray<TrainArrival> trainArrivals = loadAroundTrainArrivals(trainStations);
                final List<BikeStation> bikeStationsRes = loadAroundBikeArrivals(bikeStations);
                hideStationsAndStopsIfNeeded(busStops, busArrivalsMap, trainStations, trainArrivals);

                activity.runOnUiThread(() -> updateMarkersAndModel(busStops, busArrivalsMap, trainStations,
                        trainArrivals, bikeStationsRes));
            }, throwable -> {/*  w w w .  j a  va2 s  .c om*/
                Util.handleConnectOrParserException(throwable, null, listView, listView);
                Log.e(TAG, throwable.getMessage(), throwable);
                activity.runOnUiThread(() -> showProgress(false));
            });
}

From source file:com.intel.xdk.multitouch.MultiTouch.java

public void enableMultitouch() {
    this.multitouchQueue = new CopyOnWriteArrayList<String>();
    this.multitouchMap = new SparseArray<String>();
    this.isMultitouchEnabled = true;
}

From source file:de.damdi.fitness.activity.settings.sync.WgerJSONParser.java

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

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

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

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

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

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

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

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

            if (parsedObject == null)
                Log.e(TAG, "Could not find Locale.class: " + short_name);

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

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

    }

    return sparseArray;
}

From source file:cn.edu.zafu.easemob.imagecoverflow.CoverFlowView.java

private void init() {
    setWillNotDraw(false);/*from   ww  w .j a v  a2 s.  c o m*/
    setClickable(true);

    mChildTransformer = new Matrix();
    mReflectionTransformer = new Matrix();

    mTouchRect = new RectF();

    mImageRecorder = new SparseArray<int[]>();

    mDrawChildPaint = new Paint();
    mDrawChildPaint.setAntiAlias(true);
    mDrawChildPaint.setFlags(Paint.ANTI_ALIAS_FLAG);

    mCoverFlowPadding = new Rect();

    mDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);

    mScroller = new Scroller(getContext(), new AccelerateDecelerateInterpolator());
}

From source file:de.skubware.opentraining.activity.settings.sync.WgerJSONParser.java

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

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

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

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

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

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

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

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

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

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

            parsedObject = mDataProvider.getLicenseTypeByName(short_name);

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

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

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

    }

    return sparseArray;
}

From source file:io.appium.uiautomator2.core.AccessibilityNodeInfoDumper.java

public NodeInfoList findNodes(String xpathSelector, boolean multiple) {
    try {//from  w w w . j  a v a 2  s .c  om
        XPATH.compile(xpathSelector, Filters.element());
    } catch (IllegalArgumentException e) {
        throw new InvalidSelectorException(e);
    }

    try {
        RESOURCES_GUARD.acquire();
    } catch (InterruptedException e) {
        throw new UiAutomator2Exception(e);
    }
    uiElementsMapping = new SparseArray<>();
    try (InputStream xmlStream = toStream()) {
        final Document document = SAX_BUILDER.build(xmlStream);
        final XPathExpression<org.jdom2.Attribute> expr = XPATH
                .compile(String.format("(%s)/@%s", xpathSelector, UI_ELEMENT_INDEX), Filters.attribute());
        final NodeInfoList matchedNodes = new NodeInfoList();
        final long timeStarted = SystemClock.uptimeMillis();
        for (org.jdom2.Attribute uiElementId : expr.evaluate(document)) {
            final UiElement uiElement = uiElementsMapping.get(uiElementId.getIntValue());
            if (uiElement == null || uiElement.getNode() == null) {
                continue;
            }

            matchedNodes.add(uiElement.getNode());
            if (!multiple) {
                break;
            }
        }
        Logger.debug(String.format("Took %sms to retrieve %s matches for '%s' XPath query",
                SystemClock.uptimeMillis() - timeStarted, matchedNodes.size(), xpathSelector));
        return matchedNodes;
    } catch (JDOMParseException e) {
        throw new UiAutomator2Exception(String.format(
                "%s. " + "Try changing the '%s' driver setting to 'true' in order to workaround the problem.",
                e.getMessage(), Settings.NORMALIZE_TAG_NAMES.toString()), e);
    } catch (Exception e) {
        throw new UiAutomator2Exception(e);
    } finally {
        performCleanup();
        RESOURCES_GUARD.release();
    }
}

From source file:nya.miku.wishmaster.ui.GalleryActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        requestWindowFeature(Window.FEATURE_PROGRESS);
    settings = MainApplication.getInstance().settings;
    settings.getTheme().setTo(this, R.style.Transparent);

    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        CompatibilityImpl.setActionBarNoIcon(this);

    downloadingLocker = MainApplication.getInstance().downloadingLocker;
    inflater = getLayoutInflater();//from ww w  . j a  v a 2 s .com
    instantiatedViews = new SparseArray<View>();
    tnDownloadingTask = new CancellableTask.BaseCancellableTask();
    tnDownloadingExecutor = Executors.newFixedThreadPool(4, PriorityThreadFactory.LOW_PRIORITY_FACTORY);
    fileCache = MainApplication.getInstance().fileCache;
    bitmapCache = MainApplication.getInstance().bitmapCache;

    AttachmentModel attachment = (AttachmentModel) getIntent().getSerializableExtra(EXTRA_ATTACHMENT);
    boardModel = (BoardModel) getIntent().getSerializableExtra(EXTRA_BOARDMODEL);
    if (boardModel == null)
        return;
    String pagehash = getIntent().getStringExtra(EXTRA_PAGEHASH);
    String localFilename = getIntent().getStringExtra(EXTRA_LOCALFILENAME);
    if (localFilename != null) {
        try {
            localFile = ReadableContainer.obtain(new File(localFilename));
        } catch (Exception e) {
            Logger.e(TAG, "cannot open local file", e);
        }
    }

    chan = MainApplication.getInstance().getChanModule(boardModel.chan);
    PresentationModel presentationModel = MainApplication.getInstance().pagesCache
            .getPresentationModel(pagehash);
    if (presentationModel != null) {
        boolean isThread = presentationModel.source.pageModel.type == UrlPageModel.TYPE_THREADPAGE;
        customSubdir = BoardFragment.getCustomSubdir(presentationModel.source.pageModel);
        List<Triple<AttachmentModel, String, String>> list = presentationModel.getAttachments();
        presentationModel = null;
        if (list != null) {
            int index = -1;
            String attachmentHash = ChanModels.hashAttachmentModel(attachment);
            for (int i = 0; i < list.size(); ++i) {
                if (list.get(i).getMiddle().equals(attachmentHash)) {
                    index = i;
                    break;
                }
            }
            if (index != -1) {
                if (isThread) {
                    attachments = list;
                    currentPosition = index;
                } else {
                    int leftOffset = 0, rightOffset = 0;
                    String threadNumber = list.get(index).getRight();
                    int it = index;
                    while (it > 0 && list.get(--it).getRight().equals(threadNumber))
                        ++leftOffset;
                    it = index;
                    while (it < (list.size() - 1) && list.get(++it).getRight().equals(threadNumber))
                        ++rightOffset;
                    attachments = list.subList(index - leftOffset, index + rightOffset + 1);
                    currentPosition = leftOffset;
                }
            }
        }
    }
    if (attachments == null) {
        attachments = Collections.singletonList(
                Triple.of(attachment, ChanModels.hashAttachmentModel(attachment), (String) null));
        currentPosition = 0;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && settings.fullscreenGallery()) {
        setContentView(R.layout.gallery_layout_fullscreen);
        GalleryFullscreen.initFullscreen(this);
    } else {
        setContentView(R.layout.gallery_layout);
    }
    progressBar = (ProgressBar) findViewById(android.R.id.progress);
    progressBar.setMax(Window.PROGRESS_END);
    viewPager = (ViewPager) findViewById(R.id.gallery_viewpager);
    navigationInfo = (TextView) findViewById(R.id.gallery_navigation_info);
    for (int id : new int[] { R.id.gallery_navigation_previous, R.id.gallery_navigation_next })
        findViewById(id).setOnClickListener(this);
    viewPager.setAdapter(new GalleryAdapter());
    viewPager.setCurrentItem(currentPosition);
    viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            currentPosition = position;
            updateItem();
        }
    });
}