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

The following examples show how to use android.util.SparseArray#get() . 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: RecycleBin.java    From InfiniteViewPager with MIT License 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 2
Source File: AppWidgetHostView.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
    final Parcelable parcelable = container.get(generateId());

    SparseArray<Parcelable> jail = null;
    if (parcelable instanceof Bundle) {
        jail = ((Bundle) parcelable).getSparseParcelableArray(KEY_JAILED_ARRAY);
    }

    if (jail == null) jail = new SparseArray<>();

    try  {
        super.dispatchRestoreInstanceState(jail);
    } catch (Exception e) {
        Log.e(TAG, "failed to restoreInstanceState for widget id: " + mAppWidgetId + ", "
                + (mInfo == null ? "null" : mInfo.provider), e);
    }
}
 
Example 3
Source File: USBMonitor.java    From AndroidUSBCamera with Apache License 2.0 6 votes vote down vote up
/**
 * get interface
 * @param interface_id
 * @param altsetting
 * @return
 * @throws IllegalStateException
 */
public synchronized UsbInterface getInterface(final int interface_id, final int altsetting) throws IllegalStateException {
	checkConnection();
	SparseArray<UsbInterface> intfs = mInterfaces.get(interface_id);
	if (intfs == null) {
		intfs = new SparseArray<UsbInterface>();
		mInterfaces.put(interface_id, intfs);
	}
	UsbInterface intf = intfs.get(altsetting);
	if (intf == null) {
		final UsbDevice device = mWeakDevice.get();
		final int n = device.getInterfaceCount();
		for (int i = 0; i < n; i++) {
			final UsbInterface temp = device.getInterface(i);
			if ((temp.getId() == interface_id) && (temp.getAlternateSetting() == altsetting)) {
				intf = temp;
				break;
			}
		}
		if (intf != null) {
			intfs.append(altsetting, intf);
		}
	}
	return intf;
}
 
Example 4
Source File: AdUnitRelativeLayout.java    From unity-ads-android with Apache License 2.0 6 votes vote down vote up
public SparseArray<SparseArray<AdUnitMotionEvent>> getEvents(SparseArray<ArrayList<Integer>> requestedInfos) {
	SparseIntArray countTable = new SparseIntArray();
	SparseArray<SparseArray<AdUnitMotionEvent>> returnData = new SparseArray<>();

	synchronized (_motionEvents) {
		for (AdUnitMotionEvent currentEvent : _motionEvents) {
			ArrayList<Integer> currentRequestedInfos = requestedInfos.get(currentEvent.getAction());
			if (currentRequestedInfos != null) {
				int currentRequestedInfoIndex = currentRequestedInfos.get(0);

				if (countTable.get(currentEvent.getAction(), 0) == currentRequestedInfoIndex) {
					if (returnData.get(currentEvent.getAction()) == null) {
						returnData.put(currentEvent.getAction(), new SparseArray<AdUnitMotionEvent>());
					}

					returnData.get(currentEvent.getAction()).put(currentRequestedInfoIndex, currentEvent);
					currentRequestedInfos.remove(0);
				}

				countTable.put(currentEvent.getAction(), countTable.get(currentEvent.getAction()) + 1);
			}
		}
	}

	return returnData;
}
 
Example 5
Source File: FeatureSDLogging.java    From BlueSTSDK_Android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static Set<Feature> buildFeatureSet(Node node, long featureMask){
    Set<Feature> outList = new HashSet<>(32);
    SparseArray<Class<? extends Feature>> featureMap =
            Manager.getNodeFeatures(node.getTypeId());
    long mask= 1L<<31; //1<<31
    //we test all the 32bit of the feature mask
    for(int i=0; i<32; i++ ) {
        if ((featureMask & mask) != 0) { //if the bit is up
            Class<? extends Feature> featureClass = featureMap.get((int)mask);
            if(featureClass!=null) {
                Feature f = node.getFeature(featureClass);
                if(f!=null)
                    outList.add(f);
            }//if featureClass
        }//if mask
        mask = mask>>1;
    }//for
    return outList;
}
 
Example 6
Source File: NumberPicker.java    From iGap-Android with GNU Affero General Public License v3.0 6 votes vote down vote up
private void ensureCachedScrollSelectorValue(int selectorIndex) {
    SparseArray<String> cache = mSelectorIndexToStringCache;
    String scrollSelectorValue = cache.get(selectorIndex);
    if (scrollSelectorValue != null) {
        return;
    }
    if (selectorIndex < mMinValue || selectorIndex > mMaxValue) {
        scrollSelectorValue = "";
    } else {
        if (mDisplayedValues != null) {
            int displayedValueIndex = selectorIndex - mMinValue;
            scrollSelectorValue = mDisplayedValues[displayedValueIndex];
        } else {
            scrollSelectorValue = formatNumber(selectorIndex);
        }
    }
    cache.put(selectorIndex, scrollSelectorValue);
}
 
Example 7
Source File: RecycleBin.java    From Noyze 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 8
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 9
Source File: CoordinatorLayout.java    From ticdesign with Apache License 2.0 6 votes vote down vote up
@Override
protected void onRestoreInstanceState(Parcelable state) {
    final SavedState ss = (SavedState) state;
    super.onRestoreInstanceState(ss.getSuperState());

    final SparseArray<Parcelable> behaviorStates = ss.behaviorStates;

    for (int i = 0, count = getChildCount(); i < count; i++) {
        final View child = getChildAt(i);
        final int childId = child.getId();
        final LayoutParams lp = getResolvedLayoutParams(child);
        final Behavior b = lp.getBehavior();

        if (childId != NO_ID && b != null) {
            Parcelable savedState = behaviorStates.get(childId);
            if (savedState != null) {
                b.onRestoreInstanceState(this, child, savedState);
            }
        }
    }
}
 
Example 10
Source File: USBMonitor.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * get interface
 * @param interface_id
 * @param altsetting
 * @return
 * @throws IllegalStateException
 */
public synchronized UsbInterface getInterface(final int interface_id, final int altsetting) throws IllegalStateException {
	checkConnection();
	SparseArray<UsbInterface> intfs = mInterfaces.get(interface_id);
	if (intfs == null) {
		intfs = new SparseArray<UsbInterface>();
		mInterfaces.put(interface_id, intfs);
	}
	UsbInterface intf = intfs.get(altsetting);
	if (intf == null) {
		final UsbDevice device = mWeakDevice.get();
		final int n = device.getInterfaceCount();
		for (int i = 0; i < n; i++) {
			final UsbInterface temp = device.getInterface(i);
			if ((temp.getId() == interface_id) && (temp.getAlternateSetting() == altsetting)) {
				intf = temp;
				break;
			}
		}
		if (intf != null) {
			intfs.append(altsetting, intf);
		}
	}
	return intf;
}
 
Example 11
Source File: StorageDelegate.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * Update tab entries based on metadata.
 * @param metadataBytes Metadata from last time Chrome was alive.
 * @param entryMap Map to fill with {@link DocumentTabModel.Entry}s about Tabs.
 * @param recentlyClosedTabIdList List to fill with IDs of recently closed tabs.
 */
private void updateTabEntriesFromMetadata(byte[] metadataBytes, SparseArray<Entry> entryMap,
        List<Integer> recentlyClosedTabIdList) {
    if (metadataBytes != null) {
        DocumentList list = null;
        try {
            list = MessageNano.mergeFrom(new DocumentList(), metadataBytes);
        } catch (IOException e) {
            Log.e(TAG, "I/O exception", e);
        }
        if (list == null) return;

        for (int i = 0; i < list.entries.length; i++) {
            DocumentEntry savedEntry = list.entries[i];
            int tabId = savedEntry.tabId;

            // If the tab ID isn't in the list, it must have been closed after Chrome died.
            if (entryMap.indexOfKey(tabId) < 0) {
                recentlyClosedTabIdList.add(tabId);
                continue;
            }

            // Restore information about the Tab.
            entryMap.get(tabId).canGoBack = savedEntry.canGoBack;
        }
    }
}
 
Example 12
Source File: SectionLayoutManager.java    From toktok-android with GNU General Public License v3.0 5 votes vote down vote up
public int howManyMissingBelow(int lastPosition, @NonNull SparseArray<Boolean> positionsOffscreen) {
    int itemsSkipped = 0;
    int itemsFound = 0;
    for (int i = lastPosition;
         itemsFound < positionsOffscreen.size(); i--) {
        if (positionsOffscreen.get(i, false)) {
            itemsFound += 1;
        } else {
            itemsSkipped += 1;
        }
    }

    return itemsSkipped;
}
 
Example 13
Source File: ViewHolder.java    From LoveTalkClient with Apache License 2.0 5 votes vote down vote up
public static <T extends View> T findViewById(View view, int id) {
	SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
	if (viewHolder == null) {
		viewHolder = new SparseArray<View>();
		view.setTag(viewHolder);
	}
	View childView = viewHolder.get(id);
	if (childView == null) {
		childView = view.findViewById(id);
		viewHolder.put(id, childView);
	}
	return (T) childView;
}
 
Example 14
Source File: BaseRecyclerAdapter.java    From BmapLite with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends View> T get(View view, int id) {
    SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
    if (viewHolder == null) {
        viewHolder = new SparseArray<View>();
        view.setTag(viewHolder);
    }
    View childView = viewHolder.get(id);
    if (childView == null) {
        childView = view.findViewById(id);
        viewHolder.put(id, childView);
    }
    return (T) childView;
}
 
Example 15
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 16
Source File: EventTriggersContainer.java    From litho with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve and return an {@link EventTrigger} based on the given handle.
 *
 * @param handle
 * @return EventTrigger with the handle given.
 */
@Nullable
public synchronized EventTrigger getEventTrigger(Handle handle, int methodId) {
  if (mHandleEventTriggers == null) {
    return null;
  }

  SparseArray<EventTrigger> triggers = mHandleEventTriggers.get(handle);
  if (triggers == null) {
    return null;
  }

  return triggers.get(methodId);
}
 
Example 17
Source File: BottomSheetSlotsDialogFragment.java    From intra42 with Apache License 2.0 5 votes vote down vote up
private boolean deleteSlot(ProgressDialog progressDialog) {
    if (!deleteSlotCanBeProceed(progressDialog)) return true;
    SparseArray<Slots> verifySlots = deleteSlotGetVerificationData();

    boolean isSuccess = true;
    progressDialog.setMax(slotsGroup.group.size());
    int i = 0;

    for (Slots slot : slotsGroup.group) {
        progressDialog.setProgress(i);
        ++i;

        Slots apiData = verifySlots.get(slot.id);
        if (apiData != null && apiData.isBooked != slot.isBooked) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity, R.string.slots_delete_dialog_error_booked, Toast.LENGTH_SHORT).show();
                }
            });
            continue;
        }

        ApiService api = app.getApiService();
        Call<Slots> call = api.destroySlot(slot.id);

        try {
            if (!call.execute().isSuccessful())
                isSuccess = false;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (dialogFragment.isAdded() && !dialogFragment.isStateSaved())
        progressDialog.dismiss();
    return isSuccess;
}
 
Example 18
Source File: BackgroundAudioService.java    From YouTube-In-Background with MIT License 5 votes vote down vote up
/**
 * Get the best available audio stream
 *
 * @param ytFiles Array of available streams
 * @return Audio stream with highest bitrate
 */
private YtFile getBestStream(SparseArray<YtFile> ytFiles)
{
    Log.e(TAG, "ytFiles: " + ytFiles);
    if (ytFiles.get(YOUTUBE_ITAG_141) != null) {
        LogHelper.e(TAG, " gets YOUTUBE_ITAG_141");
        return ytFiles.get(YOUTUBE_ITAG_141);
    } else if (ytFiles.get(YOUTUBE_ITAG_140) != null) {
        LogHelper.e(TAG, " gets YOUTUBE_ITAG_140");
        return ytFiles.get(YOUTUBE_ITAG_140);
    } else if (ytFiles.get(YOUTUBE_ITAG_251) != null) {
        LogHelper.e(TAG, " gets YOUTUBE_ITAG_251");
        return ytFiles.get(YOUTUBE_ITAG_251);
    } else if (ytFiles.get(YOUTUBE_ITAG_250) != null) {
        LogHelper.e(TAG, " gets YOUTUBE_ITAG_250");
        return ytFiles.get(YOUTUBE_ITAG_250);
    } else if (ytFiles.get(YOUTUBE_ITAG_249) != null) {
        LogHelper.e(TAG, " gets YOUTUBE_ITAG_249");
        return ytFiles.get(YOUTUBE_ITAG_249);
    } else if (ytFiles.get(YOUTUBE_ITAG_171) != null) {
        LogHelper.e(TAG, " gets YOUTUBE_ITAG_171");
        return ytFiles.get(YOUTUBE_ITAG_171);
    } else if (ytFiles.get(YOUTUBE_ITAG_18) != null) {
        LogHelper.e(TAG, " gets YOUTUBE_ITAG_18");
        return ytFiles.get(YOUTUBE_ITAG_18);
    } else if (ytFiles.get(YOUTUBE_ITAG_22) != null) {
        LogHelper.e(TAG, " gets YOUTUBE_ITAG_22");
        return ytFiles.get(YOUTUBE_ITAG_22);
    } else if (ytFiles.get(YOUTUBE_ITAG_43) != null) {
        LogHelper.e(TAG, " gets YOUTUBE_ITAG_43");
        return ytFiles.get(YOUTUBE_ITAG_43);
    } else if (ytFiles.get(YOUTUBE_ITAG_36) != null) {
        LogHelper.e(TAG, " gets YOUTUBE_ITAG_36");
        return ytFiles.get(YOUTUBE_ITAG_36);
    }

    LogHelper.e(TAG, " gets YOUTUBE_ITAG_17");
    return ytFiles.get(YOUTUBE_ITAG_17);
}
 
Example 19
Source File: CsvFileDataSourceImpl.java    From AdaptiveTableLayout with MIT License 4 votes vote down vote up
List<String> getRow(int rowIndex) {
        List<String> result = new ArrayList<>();

        // cache logic. Show field after not saved changes
        List<String> cachedRow = mItemsCache.get(rowIndex);
        if (cachedRow != null && !cachedRow.isEmpty()) {
            SparseArray<String> changedRow = mChangedItems.get(rowIndex);
            if (changedRow != null && changedRow.size() > 0) {
                for (int count = cachedRow.size(), i = 0; i < count; i++) {
                    String cachedItem = cachedRow.get(i);
                    String changedItem = changedRow.get(i);
                    result.add(TextUtils.isEmpty(changedItem) ? cachedItem : changedItem);
                }
            } else {
                result.addAll(cachedRow);
            }
        }


        if (!result.isEmpty()) {
            return result;
        }

        //read from file
        InputStreamReader fileReader = null;

        try {
            fileReader = getInputStreamReader();
            int cacheRowIndex = rowIndex < READ_FILE_LINES_LIMIT ? 0 : rowIndex - READ_FILE_LINES_LIMIT;
            //skip upper lines
            Scanner scanner = new Scanner(fileReader).skip("(?:.*\\r?\\n|\\r){" + cacheRowIndex + "}");

//            for (int i = 0; i < cacheRowIndex; i++) {
//                scanner.nextLine();
//            }

            int cacheRowLimitIndex = cacheRowIndex + READ_FILE_LINES_LIMIT + READ_FILE_LINES_LIMIT;
            //on scroll to bottom
            for (int i = cacheRowIndex; i < getRowsCount() && i < cacheRowLimitIndex && scanner.hasNextLine(); i++) {
                List<String> line = new ArrayList<>(CsvUtils.parseLine(scanner.nextLine()));
                mItemsCache.put(i, line);
                if (i == rowIndex) {
                    result.addAll(line);
                }
            }

            // clear cache
            Iterator<Map.Entry<Integer, List<String>>> iterator = mItemsCache.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Integer, List<String>> entry = iterator.next();
                if (entry.getKey() < cacheRowIndex || entry.getKey() > cacheRowLimitIndex) {
                    iterator.remove();
                }
            }

        } catch (Exception e) {
            Log.e(TAG, "getRow method error ", e);
        } finally {
            ClosableUtil.closeWithoutException(fileReader);
        }

        return result;
    }
 
Example 20
Source File: WindowCache.java    From FloatUtil with MIT License 3 votes vote down vote up
/**
 * Returns the window corresponding to the id from the {@link #sWindows}
 * cache.
 * 
 * @param id
 *            The id representing the window.
 * @param cls
 *            The class of the implementation of the window.
 * @return The window corresponding to the id if it exists in the cache, or
 *         null if it does not.
 */
public Window getCache(int id, Class<? extends Context> cls) {
	SparseArray<Window> l2 = sWindows.get(cls);
	if (l2 == null) {
		return null;
	}

	return l2.get(id);
}