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:android.support.v7.internal.widget.TintManager.java

public TintManager(Context context) {
    mColorStateLists = new SparseArray<>();
    mContext = context;//w w w. ja v  a  2 s. c o  m
    mTypedValue = new TypedValue();
    mResources = new TintResources(context.getResources(), this);
}

From source file:com.forkingcode.bluetoothcompat.ScanRecordCompat.java

/**
 * Parse scan record bytes to {@link ScanRecordCompat}.
 * <p>/* w  ww  .  j a v a 2  s  . c  om*/
 * The format is defined in Bluetooth 4.1 specification, Volume 3, Part C, Section 11 and 18.
 * <p>
 * All numerical multi-byte entities and values shall use little-endian <strong>byte</strong>
 * order.
 *
 * @param scanRecord The scan record of Bluetooth LE advertisement and/or scan response.
 */
public static ScanRecordCompat parseFromBytes(byte[] scanRecord) {
    if (scanRecord == null) {
        return null;
    }

    int currentPos = 0;
    int advertiseFlag = -1;
    List<ParcelUuid> serviceUuids = new ArrayList<>();
    String localName = null;
    int txPowerLevel = Integer.MIN_VALUE;

    SparseArray<byte[]> manufacturerData = new SparseArray<>();
    Map<ParcelUuid, byte[]> serviceData = new ArrayMap<>();

    try {
        while (currentPos < scanRecord.length) {
            // length is unsigned int.
            int length = scanRecord[currentPos++] & 0xFF;
            if (length == 0) {
                break;
            }
            // Note the length includes the length of the field type itself.
            int dataLength = length - 1;
            // fieldType is unsigned int.
            int fieldType = scanRecord[currentPos++] & 0xFF;
            switch (fieldType) {
            case DATA_TYPE_FLAGS:
                advertiseFlag = scanRecord[currentPos] & 0xFF;
                break;
            case DATA_TYPE_SERVICE_UUIDS_16_BIT_PARTIAL:
            case DATA_TYPE_SERVICE_UUIDS_16_BIT_COMPLETE:
                parseServiceUuid(scanRecord, currentPos, dataLength, BluetoothUuidCompat.UUID_BYTES_16_BIT,
                        serviceUuids);
                break;
            case DATA_TYPE_SERVICE_UUIDS_32_BIT_PARTIAL:
            case DATA_TYPE_SERVICE_UUIDS_32_BIT_COMPLETE:
                parseServiceUuid(scanRecord, currentPos, dataLength, BluetoothUuidCompat.UUID_BYTES_32_BIT,
                        serviceUuids);
                break;
            case DATA_TYPE_SERVICE_UUIDS_128_BIT_PARTIAL:
            case DATA_TYPE_SERVICE_UUIDS_128_BIT_COMPLETE:
                parseServiceUuid(scanRecord, currentPos, dataLength, BluetoothUuidCompat.UUID_BYTES_128_BIT,
                        serviceUuids);
                break;
            case DATA_TYPE_LOCAL_NAME_SHORT:
            case DATA_TYPE_LOCAL_NAME_COMPLETE:
                localName = new String(extractBytes(scanRecord, currentPos, dataLength));
                break;
            case DATA_TYPE_TX_POWER_LEVEL:
                txPowerLevel = scanRecord[currentPos];
                break;
            case DATA_TYPE_SERVICE_DATA:
                // The first two bytes of the service data are service data UUID in little
                // endian. The rest bytes are service data.
                int serviceUuidLength = BluetoothUuidCompat.UUID_BYTES_16_BIT;
                byte[] serviceDataUuidBytes = extractBytes(scanRecord, currentPos, serviceUuidLength);
                ParcelUuid serviceDataUuid = BluetoothUuidCompat.parseUuidFrom(serviceDataUuidBytes);
                byte[] serviceDataArray = extractBytes(scanRecord, currentPos + serviceUuidLength,
                        dataLength - serviceUuidLength);
                serviceData.put(serviceDataUuid, serviceDataArray);
                break;
            case DATA_TYPE_MANUFACTURER_SPECIFIC_DATA:
                // The first two bytes of the manufacturer specific data are
                // manufacturer ids in little endian.
                int manufacturerId = ((scanRecord[currentPos + 1] & 0xFF) << 8)
                        + (scanRecord[currentPos] & 0xFF);
                byte[] manufacturerDataBytes = extractBytes(scanRecord, currentPos + 2, dataLength - 2);
                manufacturerData.put(manufacturerId, manufacturerDataBytes);
                break;
            default:
                // Just ignore, we don't handle such data type.
                break;
            }
            currentPos += dataLength;
        }

        if (serviceUuids.isEmpty()) {
            serviceUuids = null;
        }
        return new ScanRecordCompat(serviceUuids, manufacturerData, serviceData, advertiseFlag, txPowerLevel,
                localName, scanRecord);
    } catch (Exception e) {
        Log.e(TAG, "unable to parse scan record: " + Arrays.toString(scanRecord));
        // As the record is invalid, ignore all the parsed results for this packet
        // and return an empty record with raw scanRecord bytes in results
        return new ScanRecordCompat(null, null, null, -1, Integer.MIN_VALUE, null, scanRecord);
    }
}

From source file:com.ruesga.rview.drawer.DrawerNavigationMenuPresenter.java

@Override
public Parcelable onSaveInstanceState() {
    final Bundle state = new Bundle();
    if (mMenuView != null) {
        SparseArray<Parcelable> hierarchy = new SparseArray<>();
        mMenuView.saveHierarchyState(hierarchy);
        state.putSparseParcelableArray(STATE_HIERARCHY, hierarchy);
    }/*from   w  w  w  .j  a  v a  2  s . c  o  m*/
    if (mAdapter != null) {
        state.putBundle(STATE_ADAPTER, mAdapter.createInstanceState());
    }
    if (mHeaderLayout != null) {
        SparseArray<Parcelable> header = new SparseArray<>();
        mHeaderLayout.saveHierarchyState(header);
        state.putSparseParcelableArray(STATE_HEADER, header);
    }
    return state;
}

From source file:android.support.v17.leanback.widget.ViewsStateBundle.java

/**
 * Save views regardless what's the current policy is.
 *
 * @param view view to save/*  w  w  w .j a  va  2s .co m*/
 * @param id unique id for the view within this ViewsStateBundle
 */
protected final void saveViewUnchecked(View view, int id) {
    if (mChildStates != null) {
        String key = getSaveStatesKey(id);
        SparseArray<Parcelable> container = new SparseArray<Parcelable>();
        view.saveHierarchyState(container);
        mChildStates.put(key, container);
    }
}

From source file:org.openmrs.mobile.activities.DashboardActivity.java

private void bindDrawableResources() {
    mBitmapCache = new SparseArray<Bitmap>();
    ImageView inputFood = (ImageView) findViewById(R.id.findPatientButton);
    ImageView inputHeight = (ImageView) findViewById(R.id.registryPatientButton);
    ImageView inputExercise = (ImageView) findViewById(R.id.activeVisitsButton);
    ImageView captureVitalsImageButton = (ImageView) findViewById(R.id.captureVitalsButton);
    ImageView syncData = (ImageView) findViewById(R.id.syncData);

    createImageBitmap(R.drawable.ico_food, inputFood.getLayoutParams());
    createImageBitmap(R.drawable.ico_scale, inputHeight.getLayoutParams());
    createImageBitmap(R.drawable.ico_exercise, inputExercise.getLayoutParams());
    createImageBitmap(R.drawable.ico_vitals, captureVitalsImageButton.getLayoutParams());
    createImageBitmap(R.drawable.sync, syncData.getLayoutParams());

    inputFood.setImageBitmap(mBitmapCache.get(R.drawable.ico_food));
    inputHeight.setImageBitmap(mBitmapCache.get(R.drawable.ico_scale));
    inputExercise.setImageBitmap(mBitmapCache.get(R.drawable.ico_exercise));
    captureVitalsImageButton.setImageBitmap(mBitmapCache.get(R.drawable.ico_vitals));
    syncData.setImageBitmap(mBitmapCache.get(R.drawable.sync));
}

From source file:com.mobicage.rogerthat.NewsListAdapter.java

public void refreshView() {
    // When in pinned news never reindex
    if (!(mActivity instanceof NewsPinnedActivity)) {
        mActivity.newsPlugin.reindexSortKeys(mActivity.getFeedName());
    }// w  w  w.  j  a  v  a2  s .co m
    mNewsItemsByPosition = new SparseArray<>();
    mNewsItemsById = new LongSparseArray<>();
    mMinPosition = -1;
    mMaxPosition = -1;
    notifyDataSetChanged();
}

From source file:ru.gkpromtech.exhibition.organizations.OrganizationsFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle arguments = getArguments();/*  w  ww  .  j ava2  s  .  c  o m*/
    if (arguments != null) {
        mGroupId = arguments.getString(ARG_GROUP_ID);
        mType = arguments.getInt(ARG_TYPE);
        //noinspection unchecked
        mItems = (List<Item>) arguments.getSerializable(ARG_ITEMS);
        mFilter = arguments.getString(ARG_FILTER);
    }

    if (mItems == null) {
        DbHelper db = DbHelper.getInstance(getActivity());

        mItems = new ArrayList<>();
        Table<Organization> organizationsTable = db.getTableFor(Organization.class);
        try {
            List<Pair<Entity[], Organization>> placesOrganizations;

            if (mType == GROUPED) {
                placesOrganizations = organizationsTable.selectJoined(
                        new Table.Join[] { new Table.Join("id", PlacesOrganization.class, "organizationid"),
                                new Table.Join(Place.class, "f1.id = f0.placeid"),
                                new Table.Join(Group.class, "f2.id = f1.groupid") },
                        null, null, "f2.sortorder, t.fullname");
            } else {
                placesOrganizations = organizationsTable
                        .selectJoined(
                                new Table.Join[] {
                                        new Table.Join("id", PlacesOrganization.class, "organizationid",
                                                "LEFT"),
                                        new Table.Join(Place.class, "f1.id = f0.placeid", "LEFT"),
                                        new Table.Join(Group.class, "f2.id = f1.groupid", "LEFT") },
                                null, null, "t.fullname");
            }

            String lastTitle = null;
            int pos = 0;
            SparseArray<Item> itemsCache = new SparseArray<>();
            for (Pair<Entity[], Organization> res : placesOrganizations) {
                Place place = (Place) res.first[1];
                Organization organization = res.second;
                Group group = (Group) res.first[2];

                Item item = null;
                if (mType == GROUPED) {
                    if (!group.name.equals(lastTitle)) {
                        if (mGroupId != null && mGroupPosition == -1 && mGroupId.equals(group.position))
                            mGroupPosition = pos;
                        mItems.add(new Item(group.name));
                        ++pos;
                        lastTitle = group.name;
                    }
                } else {
                    item = itemsCache.get(organization.id);
                }

                if (item == null) {
                    item = new Item(group, place, organization);
                    item.placesStr = place.name;
                    mItems.add(item);
                    itemsCache.put(organization.id, item);
                } else {
                    if (item.addPlaces == null)
                        item.addPlaces = new ArrayList<>();
                    item.addPlaces.add(place);
                    item.placesStr += ", " + place.name;
                }
                ++pos;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    mAdapter = new OrganizationsAdapter(getActivity());
    if (mGroupPosition != -1) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                mListView.setSelection(mGroupPosition);
                if (mFilter != null)
                    onQueryTextChange(mFilter);
            }
        });
    }
}

From source file:codetoanalyze.java.checkers.ContainerWrapper.java

public void addToSparseArrayOk() {
    SparseArray sparseArray = new SparseArray();
    sparseArray.put(0, new Object());
}

From source file:com.wit.android.support.fragment.manage.BaseFragmentFactory.java

/**
 * Creates a new instance of BaseFragmentFactory. If {@link com.wit.android.support.fragment.annotation.FactoryFragments @FactoryFragments}
 * or {@link com.wit.android.support.fragment.annotation.FragmentFactories @FragmentFactories}
 * annotations are presented above a sub-class of this BaseFragmentFactory, they will be processed
 * here.//from w  w  w.  j a  v  a2 s. co  m
 */
public BaseFragmentFactory() {
    final Class<?> classOfFactory = ((Object) this).getClass();
    /**
     * Process class annotations.
     */
    final SparseArray<FragmentItem> items = new SparseArray<>();
    // Obtain fragment ids.
    if (classOfFactory.isAnnotationPresent(FactoryFragments.class)) {
        final FactoryFragments fragments = classOfFactory.getAnnotation(FactoryFragments.class);

        final int[] ids = fragments.value();
        if (ids.length > 0) {
            for (int id : ids) {
                items.put(id, new FragmentItem(id, getFragmentTag(id), null));
            }
        }
    }
    this.processAnnotatedFragments(classOfFactory, items);
    if (items.size() > 0) {
        this.mItems = items;
    }
    // Obtain joined factories.
    final List<Class<? extends FragmentController.FragmentFactory>> factories = this.gatherJoinedFactories(
            classOfFactory, new ArrayList<Class<? extends FragmentController.FragmentFactory>>());
    if (!factories.isEmpty()) {
        for (Class<? extends FragmentController.FragmentFactory> factory : factories) {
            FragmentController.FragmentFactory fragmentFactory = null;
            try {
                fragmentFactory = factory.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                Log.e(TAG, "Failed to instantiate the fragment factory class of(" + factory.getSimpleName()
                        + ")." + "Make sure this fragment factory has public empty constructor.", e);
            }
            if (fragmentFactory != null) {
                joinFactory(fragmentFactory);
            }
        }
    }
}

From source file:org.ale.scanner.zotero.MainActivity.java

@Override
public void onCreate(Bundle state) {
    super.onCreate(state);
    setContentView(R.layout.main);//  w  w  w  . j a va 2  s.  c  o m
    Bundle extras = getIntent().getExtras();

    mUIThreadHandler = new Handler();

    // Get the account we're logged in as
    mAccount = (Account) extras.getParcelable(INTENT_EXTRA_ACCOUNT);

    // Load preferences
    SharedPreferences prefs = getSharedPreferences(mAccount.getUid(), MODE_PRIVATE);
    // The group we'll upload to (default to user's personal library)
    mSelectedGroup = prefs.getInt(PREF_GROUP, Group.GROUP_LIBRARY);
    mISBNService = prefs.getInt(PREF_SERVICE, SERVICE_GOOGLE);

    // Initialize Clients
    mGoogleBooksAPI = new GoogleBooksAPIClient();
    mWorldCatAPI = new WorldCatAPIClient();
    mZAPI = new ZoteroAPIClient();
    mZAPI.setAccount(mAccount);

    // BibItem list
    ExpandableListView bibItemList = (ExpandableListView) findViewById(R.id.bib_items);

    // Pending item list
    View pendingListHolder = getLayoutInflater().inflate(R.layout.pending_item_list, bibItemList, false);
    bibItemList.addHeaderView(pendingListHolder);

    mPendingList = (ListView) pendingListHolder.findViewById(R.id.pending_item_list);

    int[] checked;
    if (state == null) { // Fresh activity
        mAccountAccess = null; // will check for permissions in onResume
        mPendingItems = new ArrayList<String>(2); // RC_PEND
        mPendingStatus = new ArrayList<Integer>(2); // RC_PEND_STAT
        checked = new int[0];
        mUploadState = UPLOAD_STATE_WAIT;
        mGroups = new SparseArray<PString>();
    } else { // Recreating activity
             // Rebuild pending list
        mAccountAccess = state.getParcelable(RC_ACCESS);
        mPendingItems = state.getStringArrayList(RC_PEND);
        mPendingStatus = state.getIntegerArrayList(RC_PEND_STAT);
        // Set checked items
        checked = state.getIntArray(RC_CHECKED);

        mUploadState = state.getInt(RC_UPLOADING);
        mGroups = state.getSparseParcelableArray(RC_GROUPS);
    }

    // Initialize list adapters
    mItemAdapter = new BibItemListAdapter(MainActivity.this);
    mItemAdapter.setChecked(checked);
    bibItemList.setAdapter(mItemAdapter);
    registerForContextMenu(bibItemList);

    mPendingAdapter = new PendingListAdapter(MainActivity.this, R.layout.pending_item, R.id.pending_item_id,
            mPendingItems, mPendingStatus);
    mPendingList.setAdapter(mPendingAdapter);
    registerForContextMenu(mPendingList);

    // Listeners
    findViewById(R.id.scan_isbn).setOnClickListener(scanIsbn);
    findViewById(R.id.upload).setOnClickListener(uploadSelected);

    // Load animations
    mAnimations = new Animation[] { AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_in_next),
            AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_out_next),
            AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_in_previous),
            AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_out_previous) };

    // Upload Bar
    findViewById(R.id.upload_progress).setOnClickListener(dismissUploadStatus);
}