android.util.SparseArray Java Examples

The following examples show how to use android.util.SparseArray. 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: MatroskaExtractor.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
MatroskaExtractor(EbmlReader reader, @Flags int flags) {
  this.reader = reader;
  this.reader.init(new InnerEbmlReaderOutput());
  seekForCuesEnabled = (flags & FLAG_DISABLE_SEEK_FOR_CUES) == 0;
  varintReader = new VarintReader();
  tracks = new SparseArray<>();
  scratch = new ParsableByteArray(4);
  vorbisNumPageSamples = new ParsableByteArray(ByteBuffer.allocate(4).putInt(-1).array());
  seekEntryIdBytes = new ParsableByteArray(4);
  nalStartCode = new ParsableByteArray(NalUnitUtil.NAL_START_CODE);
  nalLength = new ParsableByteArray(4);
  sampleStrippedBytes = new ParsableByteArray();
  subtitleSample = new ParsableByteArray();
  encryptionInitializationVector = new ParsableByteArray(ENCRYPTION_IV_SIZE);
  encryptionSubsampleData = new ParsableByteArray();
}
 
Example #2
Source File: TaskService.java    From Pretty-Zhihu with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleMessage(Message msg) {
    switch (msg.what) {
        case MSG_HUNT_COMPLETE:
            @SuppressWarnings("unchecked") SparseArray<List<String>> urls = (SparseArray<List<String>>) msg.obj;
            for (int i = 0; i < urls.size(); i++) {
                List<Picture> pictures = new ArrayList<>();
                int questionId = urls.keyAt(i);
                for (String url : urls.valueAt(i)) {
                    if (mPrettyRepository.getPicture(url, questionId) == null) {
                        Picture picture = new Picture(null, questionId, url);
                        mPrettyRepository.insertOrUpdate(picture);
                        pictures.add(picture);
                    }
                }
                if (pictures.size() > 0) {
                    EventBus.getDefault().post(new NewPictureEvent(questionId, pictures));
                    mTaskObservable.notifyFetch(questionId, pictures);
                }
            }
            break;
    }
    return false;
}
 
Example #3
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 #4
Source File: DvbParser.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
/**
 * Parses a page composition segment, as defined by ETSI EN 300 743 7.2.2.
 */
private static PageComposition parsePageComposition(ParsableBitArray data, int length) {
  int timeoutSecs = data.readBits(8);
  int version = data.readBits(4);
  int state = data.readBits(2);
  data.skipBits(2);
  int remainingLength = length - 2;

  SparseArray<PageRegion> regions = new SparseArray<>();
  while (remainingLength > 0) {
    int regionId = data.readBits(8);
    data.skipBits(8); // Skip reserved.
    int regionHorizontalAddress = data.readBits(16);
    int regionVerticalAddress = data.readBits(16);
    remainingLength -= 6;
    regions.put(regionId, new PageRegion(regionHorizontalAddress, regionVerticalAddress));
  }

  return new PageComposition(timeoutSecs, version, state, regions);
}
 
Example #5
Source File: SeatHelper.java    From Huochexing12306 with Apache License 2.0 6 votes vote down vote up
public static SparseArray<String> getSeatTypes() {
	if (seatTypes == null){
		seatTypes = new SparseArray<String>();
		seatTypes.put(SWZ, "商务座");
		seatTypes.put(TZ, "特等座");
		seatTypes.put(ZY, "一等座");
		seatTypes.put(ZE, "二等座");
		seatTypes.put(GR, "高级软卧");
		seatTypes.put(RW, "软卧");
		seatTypes.put(RZ, "软座");
		seatTypes.put(YW, "硬卧");
		seatTypes.put(YZ, "硬座");
		seatTypes.put(WZ, "无座");
	}
	return seatTypes;
}
 
Example #6
Source File: HdmiControlService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@ServiceThreadOnly
private void updateSafeMhlInput() {
    assertRunOnServiceThread();
    List<HdmiDeviceInfo> inputs = Collections.emptyList();
    SparseArray<HdmiMhlLocalDeviceStub> devices = mMhlController.getAllLocalDevices();
    for (int i = 0; i < devices.size(); ++i) {
        HdmiMhlLocalDeviceStub device = devices.valueAt(i);
        HdmiDeviceInfo info = device.getInfo();
        if (info != null) {
            if (inputs.isEmpty()) {
                inputs = new ArrayList<>();
            }
            inputs.add(device.getInfo());
        }
    }
    synchronized (mLock) {
        mMhlDevices = inputs;
    }
}
 
Example #7
Source File: Recycler.java    From AndroidAnimationExercise with Apache License 2.0 6 votes vote down vote up
static Scrap retrieveFromScrap(SparseArray<Scrap> scrapViews, int position) {
	int size = scrapViews.size();
	if (size > 0) {
		// See if we still have a view for this position.
		Scrap result = scrapViews.get(position, null);
		if (result != null) {
			scrapViews.remove(position);
			return result;
		}
		int index = size - 1;
		result = scrapViews.valueAt(index);
		scrapViews.removeAt(index);
		result.valid = false;
		return result;
	}
	return null;
}
 
Example #8
Source File: CPUFragment.java    From KernelAdiutor with GNU General Public License v3.0 6 votes vote down vote up
private void refreshCores(SparseArray<SwitchView> array, int[] freqs) {
    for (int i = 0; i < array.size(); i++) {
        SwitchView switchView = array.valueAt(i);
        if (switchView != null) {
            final int core = array.keyAt(i);
            int freq = freqs[core];

            String freqText = freq == 0 ? getString(R.string.offline) : (freq / 1000)
                    + getString(R.string.mhz);
            switchView.clearOnSwitchListener();
            switchView.setChecked(freq != 0);
            switchView.setSummary(getString(R.string.core, core + 1) + " - " + freqText);
            switchView.addOnSwitchListener((switchView1, isChecked) -> {
                if (core == 0) {
                    Utils.toast(R.string.no_offline_core, getActivity());
                } else {
                    mCPUFreq.onlineCpu(core, isChecked, true, getActivity());
                }
            });
        }
    }
}
 
Example #9
Source File: OppoVolumePanel.java    From Noyze with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override public void onCreate() {
    parentOnCreate();
    oneVolume = false;
    Context context = getContext();
    LayoutInflater inflater = LayoutInflater.from(context);

    // Load default PA color if the user doesn't have a preference.
    root = (ViewGroup) inflater.inflate(R.layout.oppo_volume_adjust, null);

    mPanel = (ViewGroup) root.findViewById(R.id.visible_panel);
    mSliderGroup = (ViewGroup) root.findViewById(R.id.slider_group);

    loadSystemSettings();

    if (null == mStreamControls)
        mStreamControls = new SparseArray<StreamControl>(StreamResources.STREAMS.length);

    // Change the icon to use for Bluetooth Music.
    MusicMode.BLUETOOTH.iconResId = R.drawable.oppo_ic_audio_bt;
    MusicMode.BLUETOOTH.iconMuteResId = R.drawable.oppo_ic_audio_bt_mute;

    mLayout = root;
}
 
Example #10
Source File: Recycler.java    From UltimateAndroid with Apache License 2.0 6 votes vote down vote up
static Scrap retrieveFromScrap(SparseArray<Scrap> scrapViews, int position) {
	int size = scrapViews.size();
	if (size > 0) {
		// See if we still have a view for this position.
		Scrap result = scrapViews.get(position, null);
		if (result != null) {
			scrapViews.remove(position);
			return result;
		}
		int index = size - 1;
		result = scrapViews.valueAt(index);
		scrapViews.removeAt(index);
		result.valid = false;
		return result;
	}
	return null;
}
 
Example #11
Source File: ChatUsersActivity.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
private TLObject getAnyParticipant(int userId) {
    boolean updated = false;
    for (int a = 0; a < 3; a++) {
        SparseArray<TLObject> map;
        if (a == 0) {
            map = contactsMap;
        } else if (a == 1) {
            map = botsMap;
        } else {
            map = participantsMap;
        }
        TLObject p = map.get(userId);
        if (p != null) {
            return p;
        }
    }
    return null;
}
 
Example #12
Source File: ProviderTvFragment.java    From xipl with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
        mFragmentSparseArray = new SparseArray<>();
        setupUI();
        showRows();
        getMainFragmentRegistry().registerFragment(PageRow.class, new TvFragmentFactory());

        if (getSearchActivity() != null) {
            TypedValue value = new TypedValue();
            TypedArray array = getActivity().obtainStyledAttributes(value.data, new int[] {android.R.attr.colorAccent});
            setSearchAffordanceColor(array.getColor(0, 0));
            setOnSearchClickedListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), getSearchActivity());
                    startActivity(intent);
                }
            });
            array.recycle();
        }
    }
}
 
Example #13
Source File: ScanRecordCompat.java    From AndroidBleManager with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a string composed from a {@link SparseArray}.
 */
static String toString(SparseArray<byte[]> array) {
    if (array == null) {
        return "null";
    }
    if (array.size() == 0) {
        return "{}";
    }
    StringBuilder buffer = new StringBuilder();
    buffer.append('{');
    for (int i = 0; i < array.size(); ++i) {
        buffer.append(array.keyAt(i)).append("=").append(Arrays.toString(array.valueAt(i)));
    }
    buffer.append('}');
    return buffer.toString();
}
 
Example #14
Source File: MediaController.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
public void setVoiceMessagesPlaylist(ArrayList<MessageObject> playlist, boolean unread) {
    voiceMessagesPlaylist = playlist;
    if (voiceMessagesPlaylist != null) {
        voiceMessagesPlaylistUnread = unread;
        voiceMessagesPlaylistMap = new SparseArray<>();
        for (int a = 0; a < voiceMessagesPlaylist.size(); a++) {
            MessageObject messageObject = voiceMessagesPlaylist.get(a);
            voiceMessagesPlaylistMap.put(messageObject.getId(), messageObject);
        }
    }
}
 
Example #15
Source File: ChunkExtractorWrapper.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param extractor The extractor to wrap.
 * @param primaryTrackType The type of the primary track. Typically one of the
 *     {@link com.google.android.exoplayer2.C} {@code TRACK_TYPE_*} constants.
 * @param primaryTrackManifestFormat A manifest defined {@link Format} whose data should be merged
 *     into any sample {@link Format} output from the {@link Extractor} for the primary track.
 */
public ChunkExtractorWrapper(Extractor extractor, int primaryTrackType,
    Format primaryTrackManifestFormat) {
  this.extractor = extractor;
  this.primaryTrackType = primaryTrackType;
  this.primaryTrackManifestFormat = primaryTrackManifestFormat;
  bindingTrackOutputs = new SparseArray<>();
}
 
Example #16
Source File: MountItemTest.java    From litho with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  mContext = new ComponentContext(getApplicationContext());

  mComponent =
      new InlineLayoutSpec() {
        @Override
        protected Component onCreateLayout(ComponentContext c) {
          return SimpleMountSpecTester.create(c).build();
        }
      };
  mComponentHost = new ComponentHost(getApplicationContext());
  mContent = new View(getApplicationContext());
  mContentDescription = "contentDescription";
  mViewTag = "tag";
  mViewTags = new SparseArray<>();
  mClickHandler = new EventHandler(mComponent, 5);
  mLongClickHandler = new EventHandler(mComponent, 3);
  mFocusChangeHandler = new EventHandler(mComponent, 9);
  mTouchHandler = new EventHandler(mComponent, 1);
  mDispatchPopulateAccessibilityEventHandler = new EventHandler(mComponent, 7);
  mFlags = 114;

  mNodeInfo = new DefaultNodeInfo();
  mNodeInfo.setContentDescription(mContentDescription);
  mNodeInfo.setClickHandler(mClickHandler);
  mNodeInfo.setLongClickHandler(mLongClickHandler);
  mNodeInfo.setFocusChangeHandler(mFocusChangeHandler);
  mNodeInfo.setTouchHandler(mTouchHandler);
  mNodeInfo.setViewTag(mViewTag);
  mNodeInfo.setViewTags(mViewTags);
  mMountItem = create(mContent);
}
 
Example #17
Source File: SlideListView.java    From SlideAndDragListView with Apache License 2.0 5 votes vote down vote up
/**
 * 设置Menu
 *
 * @param menu
 */
public void setMenu(Menu menu) {
    if (mMenuSparseArray != null) {
        mMenuSparseArray.clear();
    } else {
        mMenuSparseArray = new SparseArray<>();
    }
    mMenuSparseArray.put(menu.getMenuViewType(), menu);
}
 
Example #18
Source File: BaseScene.java    From EhViewer with Apache License 2.0 5 votes vote down vote up
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);

    if (drawerView != null) {
        drawerViewState = new SparseArray<>();
        drawerView.saveHierarchyState(drawerViewState);
        outState.putSparseParcelableArray(KEY_DRAWER_VIEW_STATE, drawerViewState);
    }
}
 
Example #19
Source File: InstantAppRegistry.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void removeAppLPw(@UserIdInt int userId, int targetAppId) {
    // remove from the installed list
    if (mInstantGrants == null) {
        return; // no grants on the system
    }
    final SparseArray<SparseBooleanArray> targetAppList = mInstantGrants.get(userId);
    if (targetAppList == null) {
        return; // no grants for this user
    }
    targetAppList.delete(targetAppId);
}
 
Example #20
Source File: BaseViewHolder.java    From NIM_Android_UIKit with MIT License 5 votes vote down vote up
public BaseViewHolder(View view) {
    super(view);
    this.views = new SparseArray<View>();
    this.childClickViewIds = new LinkedHashSet<>();
    this.itemChildLongClickViewIds = new LinkedHashSet<>();
    convertView = view;

}
 
Example #21
Source File: AudioFlingerProxy.java    From Noyze with Apache License 2.0 5 votes vote down vote up
protected float getStreamIncrement(int stream) throws RemoteException {
    // Figure out what the increment is.
    SparseArray<Float> map = mStreamStepMap.get(stream);
    int indexOne = map.keyAt(0);
    int indexTwo = map.keyAt(1);
    float valueOne = map.get(indexOne);
    float valueTwo = map.get(indexTwo);

    return  Math.abs(valueTwo - valueOne) /
            Math.abs(indexTwo - indexOne);
}
 
Example #22
Source File: DownloadActivity.java    From YouTube-In-Background with MIT License 5 votes vote down vote up
private void getYoutubeDownloadUrl(String youtubeLink)
{
    new YouTubeExtractor(this)
    {
        @Override
        public void onExtractionComplete(SparseArray<YtFile> ytFiles, VideoMeta vMeta)
        {
            mainProgressBar.setVisibility(View.GONE);
            if (ytFiles == null) {
                TextView tv = new TextView(getActivityContext());
                tv.setText(R.string.app_update);
                tv.setMovementMethod(LinkMovementMethod.getInstance());
                mainLayout.addView(tv);
                return;
            }
            formatsToShowList = new ArrayList<>();
            for (int i = 0, itag; i < ytFiles.size(); i++) {
                itag = ytFiles.keyAt(i);
                YtFile ytFile = ytFiles.get(itag);

                if (ytFile.getFormat().getHeight() == -1 || ytFile.getFormat().getHeight() >= 360) {
                    addFormatToList(ytFile, ytFiles);
                }
            }
            Collections.sort(formatsToShowList, new Comparator<YouTubeFragmentedVideo>()
            {
                @Override
                public int compare(YouTubeFragmentedVideo lhs, YouTubeFragmentedVideo rhs)
                {
                    return lhs.height - rhs.height;
                }
            });
            for (YouTubeFragmentedVideo files : formatsToShowList) {
                addButtonToMainLayout(vMeta.getTitle(), files);
            }
        }
    }.extract(youtubeLink, true, false);
}
 
Example #23
Source File: CpuSpyApp.java    From SmartPack-Kernel-Manager with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Load the saved string of offsets from preferences and put it into the
 * state monitor
 */
private void loadOffsets(Context context) {
    String prefs = Prefs.getString(PREF_OFFSETS, "", context);

    if (prefs.isEmpty()) return;
    // split the string by peroids and then the info by commas and load
    SparseArray<Long> offsets = new SparseArray<>();
    String[] sOffsets = prefs.split(",");
    for (String offset : sOffsets) {
        String[] parts = offset.split(" ");
        offsets.put(Utils.strToInt(parts[0]), Utils.strToLong(parts[1]));
    }

    mMonitor.setOffsets(offsets);
}
 
Example #24
Source File: SeatHelper.java    From Huochexing12306 with Apache License 2.0 5 votes vote down vote up
private int getIndexOfValue(SparseArray<String> sa1, String strValue){
	for(int i=0; i<sa1.size(); i++){
		if (strValue.equals(sa1.valueAt(i))){
			return i;
		}
	}
	return -1;
}
 
Example #25
Source File: ManagerTest.java    From BlueSTSDK_Android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test(expected = InvalidFeatureBitMaskException.class)
public void addInvalidFeatureMask() throws InvalidFeatureBitMaskException{
    SparseArray<Class<? extends Feature>> invalidMask = new SparseArray<>(1);
    invalidMask.append(3, Feature.class); //not a power of 2

    Manager.addFeatureToNode((byte) 0x00, invalidMask);
}
 
Example #26
Source File: MapStore.java    From intra42 with Apache License 2.0 5 votes vote down vote up
public Location get(int x, int y) {
    if (x < 0 || y < 0)
        return null;
    SparseArray<Location> col = super.get(x);
    if (col == null)
        return null;
    return col.get(y);
}
 
Example #27
Source File: DataBindParser.java    From android-databinding with Apache License 2.0 5 votes vote down vote up
/**
 * apply the data by target view, often used for adapter
 * @param info  may be {@link com.heaven7.databinding.core.DataBindParser.ImagePropertyBindInfo}
 */
private static void applyDataReally(View v, int layoutId,PropertyBindInfo info, ViewHelper vp,
                                    IDataResolver dr,SparseArray<ListenerImplContext> mListenerMap,
                                    EventParseCaretaker caretaker) {
    if(info instanceof ImagePropertyBindInfo){
        checkAndGetImageApplier().apply((ImageView) v, dr, (ImagePropertyBindInfo) info);
        //applyImageProperty(v, dr, (ImagePropertyBindInfo) info);
    }else {
        final int id = v.hashCode();
        caretaker.beginParse(id, layoutId, info.propertyName, mListenerMap);
        final Object val = info.realExpr.evaluate(dr);
        caretaker.endParse();
        apply(null, v, id, layoutId, info.propertyName, val, mListenerMap);
    }
}
 
Example #28
Source File: Manager.java    From BlueSTSDK_Android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * register a new device id or add feature to an already defined device
 * <p>the change will affect only the node discover after this call</p>
 * @param deviceId device type that will use the feature, it can be a new device id
 * @param features array of feature that we will add, the index of the feature will be used
 *                 as feature mask. the feature mask must have only one bit to 1
 * @throws InvalidFeatureBitMaskException throw when a feature is a position that is not a
 * power of 2
 */
public static void addFeatureToNode(byte deviceId,SparseArray<Class<? extends Feature>> features)
        throws InvalidFeatureBitMaskException {
    SparseArray<Class<? extends Feature>> updateMe;
    if(!sFeatureMapDecoder.containsKey(deviceId)){
        updateMe = BLENodeDefines.FeatureCharacteristics.DEFAULT_MASK_TO_FEATURE.clone();
        sFeatureMapDecoder.put(deviceId,updateMe);
    }else{
        updateMe = sFeatureMapDecoder.get(deviceId);
    }//if-else

    SparseArray<Class<? extends Feature>> addMe = features.clone();

    long mask=1;
    //we test all the 32bit of the feature mask
    for(int i=0; i<32; i++ ){
        Class<? extends Feature> featureClass = addMe.get((int)mask);
        if (featureClass != null) {
            updateMe.append((int) mask, featureClass);
            addMe.remove((int)mask);
        }
        mask=mask<<1;
    }//for

    if(addMe.size()!=0)
        throw new InvalidFeatureBitMaskException("Not all elements have a single bit in " +
                "as key");
}
 
Example #29
Source File: BaseViewHolder.java    From demo4Fish with MIT License 5 votes vote down vote up
public BaseViewHolder(final View view) {
    super(view);
    this.views = new SparseArray<View>();
    this.childClickViewIds = new LinkedHashSet<>();
    this.itemChildLongClickViewIds = new LinkedHashSet<>();
    this.nestViews = new HashSet<>();
    convertView = view;


}
 
Example #30
Source File: TsExtractor.java    From Exoplayer_VLC with Apache License 2.0 5 votes vote down vote up
public TsExtractor(boolean shouldSpliceIn, long firstSampleTimestamp, BufferPool bufferPool) {
  super(shouldSpliceIn);
  this.firstSampleTimestamp = firstSampleTimestamp;
  this.bufferPool = bufferPool;
  tsScratch = new ParsableBitArray(new byte[3]);
  tsPacketBuffer = new ParsableByteArray(TS_PACKET_SIZE);
  sampleQueues = new SparseArray<SampleQueue>();
  tsPayloadReaders = new SparseArray<TsPayloadReader>();
  tsPayloadReaders.put(TS_PAT_PID, new PatReader());
  lastPts = Long.MIN_VALUE;
}