Java Code Examples for android.util.LongSparseArray

The following are top voted examples for showing how to use android.util.LongSparseArray. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Phoenix-for-VK   File: MessagesDecryptor.java   View source code 6 votes vote down vote up
private Single<LongSparseArray<AesKeyPair>> getKeyPairs(final int accountId, final List<Pair<Integer, Long>> tokens) {
    return Single.create(emitter -> {
        LongSparseArray<AesKeyPair> keys = new LongSparseArray<>(tokens.size());

        for (Pair<Integer, Long> token : tokens) {
            if (emitter.isDisposed()) {
                break;
            }

            final long sessionId = token.getSecond();
            final int keyPolicy = token.getFirst();

            AesKeyPair keyPair = store.keys(keyPolicy).findKeyPairFor(accountId, sessionId).blockingGet();

            if (nonNull(keyPair)) {
                keys.append(sessionId, keyPair);
            }
        }

        emitter.onSuccess(keys);
    });
}
 
Example 2
Project: atlas   File: DelegateResources.java   View source code 6 votes vote down vote up
public static void walkroundActionMenuTextColor(Resources res){
    try {
        if (Build.VERSION.SDK_INT>=16 && Build.VERSION.SDK_INT <= 19) {
            final long key = (((long) -1) << 32) | 0x7f010082;
            if(walkroundStateList==null) {
                walkroundStateList = ColorStateList.valueOf(Color.rgb(0, 0, 0));
            }
            Field mColorStateListCacheField = AndroidHack.findField(res, "mColorStateListCache");
            mColorStateListCacheField.setAccessible(true);
            LongSparseArray mColorStateListCache = (LongSparseArray) mColorStateListCacheField.get(res);
            mColorStateListCache.put(key,new WeakReference<>(walkroundStateList));
        }
    }catch(Throwable e){
        e.printStackTrace();
    }
}
 
Example 3
Project: androidtv-sample   File: TvContractUtils.java   View source code 6 votes vote down vote up
public static LongSparseArray<XmlTvParser.XmlTvChannel> buildChannelMap(
        ContentResolver resolver, String inputId, List<XmlTvParser.XmlTvChannel> channels) {
    Uri uri = TvContract.buildChannelsUriForInput(inputId);
    String[] projection = {
            TvContract.Channels._ID,
            TvContract.Channels.COLUMN_DISPLAY_NUMBER
    };

    LongSparseArray<XmlTvParser.XmlTvChannel> channelMap = new LongSparseArray<>();
    try (Cursor cursor = resolver.query(uri, projection, null, null, null)) {
        if (cursor == null || cursor.getCount() == 0) {
            return null;
        }

        while (cursor.moveToNext()) {
            long channelId = cursor.getLong(0);
            String channelNumber = cursor.getString(1);
            channelMap.put(channelId, getChannelByNumber(channelNumber, channels));
        }
    } catch (Exception e) {
        Log.d(TAG, "Content provider query: " + Arrays.toString(e.getStackTrace()));
        return null;
    }
    return channelMap;
}
 
Example 4
Project: exciting-app   File: AbsHListView.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void setAdapter(ListAdapter adapter) {
	if (adapter != null) {
		mAdapterHasStableIds = mAdapter.hasStableIds();
		if (mChoiceMode != AbsListView.CHOICE_MODE_NONE
				&& mAdapterHasStableIds && mCheckedIdStates == null) {
			mCheckedIdStates = new LongSparseArray<Integer>();
		}
	}

	if (mCheckStates != null) {
		mCheckStates.clear();
	}

	if (mCheckedIdStates != null) {
		mCheckedIdStates.clear();
	}
}
 
Example 5
Project: exciting-app   File: AbsHListView.java   View source code 6 votes vote down vote up
/**
 * Returns the set of checked items ids. The result is only valid if the
 * choice mode has not been set to {@link #CHOICE_MODE_NONE} and the adapter
 * has stable IDs. ({@link ListAdapter#hasStableIds()} == {@code true})
 * 
 * @return A new array which contains the id of each checked item in the
 *         list.
 */
public long[] getCheckedItemIds() {
	if (mChoiceMode == AbsListView.CHOICE_MODE_NONE
			|| mCheckedIdStates == null || mAdapter == null) {
		return new long[0];
	}

	final LongSparseArray<Integer> idStates = mCheckedIdStates;
	final int count = idStates.size();
	final long[] ids = new long[count];

	for (int i = 0; i < count; i++) {
		ids[i] = idStates.keyAt(i);
	}

	return ids;
}
 
Example 6
Project: MessageOnTap_API   File: LongSparseArrayTypeAdapter.java   View source code 6 votes vote down vote up
@Override
public LongSparseArray<T> read(JsonReader jsonReader) throws IOException {
    if (jsonReader.peek() == JsonToken.NULL) {
        jsonReader.nextNull();
        return null;
    }
    LongSparseArray<Object> temp = gson.fromJson(jsonReader, typeOfLongSparseArrayOfObject);
    LongSparseArray<T> result = new LongSparseArray<>(temp.size());
    long key;
    JsonElement tElement;
    for (int i = 0, size = temp.size(); i < size; ++i) {
        key = temp.keyAt(i);
        tElement = gson.toJsonTree(temp.get(key));
        result.put(key, (T) JSONUtils.jsonToSimpleObject(tElement.toString(), typeOfT));
    }
    return result;
}
 
Example 7
Project: android_packages_apps_tv   File: SeriesRecordingSchedulerTest.java   View source code 6 votes vote down vote up
public void testPickOneProgramPerEpisode_manyPerEpisode() {
    SeriesRecording seriesRecording = SeriesRecording.buildFrom(mBaseSeriesRecording)
            .setId(SERIES_RECORDING_ID1).build();
    mDataManager.addSeriesRecording(seriesRecording);
    List<Program> programs = new ArrayList<>();
    Program program1 = new Program.Builder(mBaseProgram).setSeasonNumber(SEASON_NUMBER1)
            .setEpisodeNumber(EPISODE_NUMBER1).setStartTimeUtcMillis(0).build();
    programs.add(program1);
    Program program2 = new Program.Builder(program1).setStartTimeUtcMillis(1).build();
    programs.add(program2);
    Program program3 = new Program.Builder(mBaseProgram).setSeasonNumber(SEASON_NUMBER2)
            .setEpisodeNumber(EPISODE_NUMBER2).build();
    programs.add(program3);
    Program program4 = new Program.Builder(program1).setStartTimeUtcMillis(1).build();
    programs.add(program4);
    LongSparseArray<List<Program>> result = SeriesRecordingScheduler.pickOneProgramPerEpisode(
            mDataManager, Collections.singletonList(seriesRecording), programs);
    MoreAsserts.assertContentsInAnyOrder(result.get(SERIES_RECORDING_ID1), program1, program3);
}
 
Example 8
Project: ticdesign   File: TrackSelectionAdapterWrapper.java   View source code 6 votes vote down vote up
/**
 * Defines the choice behavior for the List. By default, Lists do not have any choice behavior
 * ({@link AbsListView#CHOICE_MODE_NONE}). By setting the choiceMode to {@link AbsListView#CHOICE_MODE_SINGLE}, the
 * List allows up to one item to  be in a chosen state. By setting the choiceMode to
 * {@link AbsListView#CHOICE_MODE_MULTIPLE}, the list allows any number of items to be chosen.
 *
 * @param choiceMode One of {@link AbsListView#CHOICE_MODE_NONE}, {@link AbsListView#CHOICE_MODE_SINGLE}, or
 * {@link AbsListView#CHOICE_MODE_MULTIPLE}
 */
public void setChoiceMode(int choiceMode) {
    mChoiceMode = choiceMode;
    if (mChoiceActionMode != null) {
        mChoiceActionMode.finish();
        mChoiceActionMode = null;
    }
    if (mChoiceMode != AbsListView.CHOICE_MODE_NONE) {
        if (mCheckStates == null) {
            mCheckStates = new SparseBooleanArray(0);
        }
        if (mCheckedIdStates == null && hasStableIds()) {
            mCheckedIdStates = new LongSparseArray<Integer>(0);
        }
        // Modal multi-choice mode only has choices when the mode is active. Clear them.
        if (mChoiceMode == AbsListView.CHOICE_MODE_MULTIPLE_MODAL) {
            clearChoices();
            if (mAttachedRecyclerView != null) {
                mAttachedRecyclerView.setLongClickable(true);
            }
        }
    }
}
 
Example 9
Project: ticdesign   File: TrackSelectionAdapterWrapper.java   View source code 6 votes vote down vote up
/**
 * Returns the set of checked items ids. The result is only valid if the
 * choice mode has not been set to {@link AbsListView#CHOICE_MODE_NONE} and the adapter
 * has stable IDs. ({@link ListAdapter#hasStableIds()} == {@code true})
 *
 * @return A new array which contains the id of each checked item in the
 *         list.
 */
public long[] getCheckedItemIds() {
    if (mChoiceMode == AbsListView.CHOICE_MODE_NONE || mCheckedIdStates == null) {
        return new long[0];
    }

    final LongSparseArray<Integer> idStates = mCheckedIdStates;
    final int count = idStates.size();
    final long[] ids = new long[count];

    for (int i = 0; i < count; i++) {
        ids[i] = idStates.keyAt(i);
    }

    return ids;
}
 
Example 10
Project: StreetComplete   File: OverpassMapDataParserTest.java   View source code 6 votes vote down vote up
private Element parseOne(String xml, LongSparseArray<List<LatLon>> expectedGeometry)
{
	SingleElementHandler handler = new SingleElementHandler();
	OverpassMapDataParser parser = new OverpassMapDataParser(
			new TestElementGeometryCreator(expectedGeometry), new OsmMapDataFactory());
	parser.setHandler(handler);
	try
	{
		parser.parse(asInputStream(xml));
	}
	catch (IOException e)
	{
		throw new RuntimeException(e);
	}

	return handler.element;
}
 
Example 11
Project: appium-uiautomator2-server   File: ActionsHelpers.java   View source code 6 votes vote down vote up
private static void applyEmptyActionToEventsMapping(
        final JSONObject action, final LongSparseArray<List<InputEventParams>> mapping)
        throws JSONException {
    final JSONArray actionItems = action.getJSONArray(ACTION_KEY_ACTIONS);
    long timeDelta = 0;
    for (int i = 0; i < actionItems.length(); i++) {
        final JSONObject actionItem = actionItems.getJSONObject(i);
        final String itemType = actionItem.getString(ACTION_ITEM_TYPE_KEY);
        if (!itemType.equals(ACTION_ITEM_TYPE_PAUSE)) {
            throw new ActionsParseException(String.format(
                    "Unexpected action item %s '%s' in action with id '%s'",
                    ACTION_ITEM_TYPE_KEY, itemType, action.getString(ACTION_KEY_ID)));
        }
        timeDelta += extractDuration(action, actionItem);
        recordEventParams(timeDelta, mapping, null);
    }
}
 
Example 12
Project: appium-uiautomator2-server   File: ActionsHelpers.java   View source code 6 votes vote down vote up
public static LongSparseArray<List<InputEventParams>> actionsToInputEventsMapping(
        final JSONArray actions) throws JSONException {
    final LongSparseArray<List<InputEventParams>> result = new LongSparseArray<>();
    final List<JSONObject> pointerActions = filterActionsByType(actions, ACTION_TYPE_POINTER);
    for (int pointerIdx = 0; pointerIdx < pointerActions.size(); pointerIdx++) {
        applyPointerActionToEventsMapping(pointerActions.get(pointerIdx), pointerIdx, result);
    }
    final List<JSONObject> keyInputActions = filterActionsByType(actions, ACTION_TYPE_KEY);
    for (final JSONObject keyAction : keyInputActions) {
        applyKeyActionToEventsMapping(keyAction, result);
    }
    final List<JSONObject> emptyActions = filterActionsByType(actions, ACTION_TYPE_NONE);
    for (final JSONObject emptyAction : emptyActions) {
        applyEmptyActionToEventsMapping(emptyAction, result);
    }
    return result;
}
 
Example 13
Project: appium-uiautomator2-server   File: W3CActionsTransformationTests.java   View source code 6 votes vote down vote up
@Test
public void verifyValidInputEventsChainIsCompiledForNoneAction() throws JSONException {
    final JSONArray actionJson = new JSONArray("[ {" +
            "\"type\": \"none\"," +
            "\"id\": \"none1\"," +
            "\"actions\": [" +
            "{\"type\": \"pause\", \"duration\": 200}," +
            "{\"type\": \"pause\", \"duration\": 20}]" +
            "} ]");
    final LongSparseArray<List<InputEventParams>> eventsChain = actionsToInputEventsMapping(
            preprocessActions(actionJson)
    );
    assertThat(eventsChain.size(), equalTo(2));

    assertThat(eventsChain.keyAt(0), equalTo(200L));
    assertThat(eventsChain.valueAt(0).size(), equalTo(0));

    assertThat(eventsChain.keyAt(1), equalTo(220L));
    assertThat(eventsChain.valueAt(1).size(), equalTo(0));
}
 
Example 14
Project: CodeColors   File: CcDrawableCache.java   View source code 6 votes vote down vote up
public CcDrawableCache(Context context, LongSparseArray<Drawable.ConstantState> cache) {
    mResources = context.getApplicationContext().getResources();
    mPackageName = context.getApplicationContext().getPackageName();

    if (cache != null) {
        mCheckDependenciesKeys = new HashSet<>(cache.size());

        int N = cache.size();
        for (int i = 0; i < N; i++) {
            long key = cache.keyAt(i);
            mCheckDependenciesKeys.add(key);
            put(key, cache.valueAt(i));
        }
    } else {
        mCheckDependenciesKeys = new HashSet<>(0);
    }
}
 
Example 15
Project: CodeColors   File: CcColorCache.java   View source code 6 votes vote down vote up
public CcColorCache(Context context, LongSparseArray cache) {
    mResources = context.getApplicationContext().getResources();
    mPackageName = context.getApplicationContext().getPackageName();

    if (cache != null) {
        mCheckDependenciesKeys = new HashSet<>(cache.size());

        int N = cache.size();
        for (int i = 0; i < N; i++) {
            long key = cache.keyAt(i);
            mCheckDependenciesKeys.add(key);
            put(key, cache.valueAt(i));
        }
    } else {
        mCheckDependenciesKeys = new HashSet<>(0);
    }
}
 
Example 16
Project: sprockets-android   File: SparseArrays.java   View source code 6 votes vote down vote up
private static <E> Object values(SparseArray<E> a, SparseBooleanArray b, SparseIntArray c,
                                 SparseLongArray d, LongSparseArray<E> e) {
    int size = size(a, b, c, d, e);
    ArrayList<E> vals = a != null || e != null ? new ArrayList<>(size) : null;
    boolean[] bools = b != null ? new boolean[size] : null;
    int[] ints = c != null ? new int[size] : null;
    long[] longs = d != null ? new long[size] : null;
    for (int i = 0; i < size; i++) {
        if (vals != null) {
            vals.add(a != null ? a.valueAt(i) : e.valueAt(i));
        } else if (bools != null) {
            bools[i] = b.valueAt(i);
        } else if (ints != null) {
            ints[i] = c.valueAt(i);
        } else if (longs != null) {
            longs[i] = d.valueAt(i);
        }
    }
    return vals != null ? vals : bools != null ? bools : ints != null ? ints : longs;
}
 
Example 17
Project: AndroidClient   File: TwoWayView.java   View source code 6 votes vote down vote up
/**
 * Returns the set of checked items ids. The result is only valid if the
 * choice mode has not been set to {@link #CHOICE_MODE_NONE} and the adapter
 * has stable IDs. ({@link ListAdapter#hasStableIds()} == {@code true})
 *
 * @return A new array which contains the id of each checked item in the
 *         list.
 */
public long[] getCheckedItemIds() {
    if (mChoiceMode.compareTo(ChoiceMode.NONE) == 0 ||
            mCheckedIdStates == null || mAdapter == null) {
        return new long[0];
    }

    final LongSparseArray<Integer> idStates = mCheckedIdStates;
    final int count = idStates.size();
    final long[] ids = new long[count];

    for (int i = 0; i < count; i++) {
        ids[i] = idStates.keyAt(i);
    }

    return ids;
}
 
Example 18
Project: AndroidClient   File: TwoWayView.java   View source code 6 votes vote down vote up
/**
 * Constructor called from {@link #CREATOR}
 */
private SavedState(Parcel in) {
    super(in);

    selectedId = in.readLong();
    firstId = in.readLong();
    viewStart = in.readInt();
    position = in.readInt();
    height = in.readInt();

    checkedItemCount = in.readInt();
    checkState = in.readSparseBooleanArray();

    final int N = in.readInt();
    if (N > 0) {
        checkIdState = new LongSparseArray<Integer>();
        for (int i = 0; i < N; i++) {
            final long key = in.readLong();
            final int value = in.readInt();
            checkIdState.put(key, value);
        }
    }
}
 
Example 19
Project: hwo2014_FireEdge   File: CurvesDB.java   View source code 6 votes vote down vote up
public static void load(LongSparseArray<SwitchRadiusInfo[]> weirdBendedSwitchesInfo) {
    if (weirdBendedSwitchesInfo.size() == 0) {
        try {
            InputStream is = CurvesDB.class.getResourceAsStream("/curves.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
            CurvesJson.Curves[] curves = new Gson().fromJson(reader, CurvesJson.class).curves;
            int pointsCount = 0;
            for (CurvesJson.Curves curve : curves) {
                SwitchRadiusInfo[] values = new SwitchRadiusInfo[curve.values.length / 2];
                for (int i = 0; i < curve.values.length; i += 2) {
                    values[i / 2] = new SwitchRadiusInfo(curve.values[i], curve.values[i + 1]);
                }
                pointsCount += curve.values.length / 2;
                weirdBendedSwitchesInfo.put(curve.key, values);
            }
            System.out.println("Loaded " + curves.length + " curves, " + pointsCount + " points.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example 20
Project: LaunchEnr   File: ImportDataTask.java   View source code 5 votes vote down vote up
private boolean importWorkspace() throws Exception {
    ArrayList<Long> allScreens = LauncherDbUtils.getScreenIdsFromCursor(
            mContext.getContentResolver().query(mOtherScreensUri, null, null, null,
                    LauncherSettings.WorkspaceScreens.SCREEN_RANK));


    // During import we reset the screen IDs to 0-indexed values.
    if (allScreens.isEmpty()) {
        // No thing to migrate

        return false;
    }

    mHotseatSize = mMaxGridSizeX = mMaxGridSizeY = 0;

    // Build screen update
    ArrayList<ContentProviderOperation> screenOps = new ArrayList<>();
    int count = allScreens.size();
    LongSparseArray<Long> screenIdMap = new LongSparseArray<>(count);
    for (int i = 0; i < count; i++) {
        ContentValues v = new ContentValues();
        v.put(LauncherSettings.WorkspaceScreens._ID, i);
        v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
        screenIdMap.put(allScreens.get(i), (long) i);
        screenOps.add(ContentProviderOperation.newInsert(
                LauncherSettings.WorkspaceScreens.CONTENT_URI).withValues(v).build());
    }
    mContext.getContentResolver().applyBatch(ProviderConfig.AUTHORITY, screenOps);
    importWorkspaceItems(allScreens.get(0), screenIdMap);

    GridSizeMigrationTask.markForMigration(mContext, mMaxGridSizeX, mMaxGridSizeY, mHotseatSize);

    // Create empty DB flag.
    LauncherSettings.Settings.call(mContext.getContentResolver(),
            LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG);
    return true;
}
 
Example 21
Project: Phoenix-for-VK   File: KeyExchangeService.java   View source code 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mCurrentActiveSessions = new LongSparseArray<>(1);
    mCurrentActiveNotifications = new LongSparseArray<>(1);
    mFinishedSessionsIds = new HashSet<>(1);
}
 
Example 22
Project: androidtv-sample   File: SyncAdapter.java   View source code 5 votes vote down vote up
/**
 * Called periodically by the system in every {@code FULL_SYNC_FREQUENCY_SEC}.
 */
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {
    Log.d(TAG, "onPerformSync(" + account + ", " + authority + ", " + extras + ")");
    String inputId = extras.getString(SyncAdapter.BUNDLE_KEY_INPUT_ID);
    if (inputId == null) {
        return;
    }
    XmlTvParser.TvListing listings = RichFeedUtil.getRichTvListings(mContext);
    LongSparseArray<XmlTvParser.XmlTvChannel> channelMap = TvContractUtils.buildChannelMap(
            mContext.getContentResolver(), inputId, listings.channels);
    boolean currentProgramOnly = extras.getBoolean(
            SyncAdapter.BUNDLE_KEY_CURRENT_PROGRAM_ONLY, false);
    long startMs = System.currentTimeMillis();
    long endMs = startMs + FULL_SYNC_WINDOW_SEC * 1000;
    if (currentProgramOnly) {
        // This is requested from the setup activity, in this case, users don't need to wait for
        // the full sync. Sync the current programs first and do the full sync later in the
        // background.
        endMs = startMs + SHORT_SYNC_WINDOW_SEC * 1000;
    }
    for (int i = 0; i < channelMap.size(); ++i) {
        Uri channelUri = TvContract.buildChannelUri(channelMap.keyAt(i));
        List<Program> programs = getPrograms(channelUri, channelMap.valueAt(i),
                listings.programs, startMs, endMs);
        updatePrograms(channelUri, programs);
    }
}
 
Example 23
Project: exciting-app   File: AbsHListView.java   View source code 5 votes vote down vote up
/**
 * Defines the choice behavior for the List. By default, Lists do not have
 * any choice behavior ({@link #CHOICE_MODE_NONE}). By setting the
 * choiceMode to {@link #CHOICE_MODE_SINGLE}, the List allows up to one item
 * to be in a chosen state. By setting the choiceMode to
 * {@link #CHOICE_MODE_MULTIPLE}, the list allows any number of items to be
 * chosen.
 * 
 * @param choiceMode
 *            One of {@link #CHOICE_MODE_NONE}, {@link #CHOICE_MODE_SINGLE},
 *            or {@link #CHOICE_MODE_MULTIPLE}
 */
@TargetApi(11)
public void setChoiceMode(int choiceMode) {
	mChoiceMode = choiceMode;

	if (android.os.Build.VERSION.SDK_INT >= 11) {
		if (mChoiceActionMode != null) {

			if (android.os.Build.VERSION.SDK_INT >= 11) {
				((ActionMode) mChoiceActionMode).finish();
			}
			mChoiceActionMode = null;
		}
	}

	if (mChoiceMode != AbsListView.CHOICE_MODE_NONE) {
		if (mCheckStates == null) {
			mCheckStates = new SparseArrayCompat<Boolean>();
		}
		if (mCheckedIdStates == null && mAdapter != null
				&& mAdapter.hasStableIds()) {
			mCheckedIdStates = new LongSparseArray<Integer>();
		}
		// Modal multi-choice mode only has choices when the mode is active.
		// Clear them.
		if (android.os.Build.VERSION.SDK_INT >= 11) {
			if (mChoiceMode == AbsListView.CHOICE_MODE_MULTIPLE_MODAL) {
				clearChoices();
				setLongClickable(true);
			}
		}
	}
}
 
Example 24
Project: exciting-app   File: AbsHListView.java   View source code 5 votes vote down vote up
private LongSparseArray<Integer> readSparseLongArray(Parcel in) {
	if (LOG_ENABLED) {
		Log.i(TAG, "readSparseLongArray");
	}
	final int N = in.readInt();
	if (N <= 0) {
		return null;
	}
	LongSparseArray<Integer> array = new LongSparseArray<Integer>(N);
	readSparseLongArrayInternal(array, in, N);
	return array;
}
 
Example 25
Project: exciting-app   File: AbsHListView.java   View source code 5 votes vote down vote up
private void readSparseLongArrayInternal(
		LongSparseArray<Integer> outVal, Parcel in, int N) {
	while (N > 0) {
		final long key = in.readLong();
		final int value = in.readInt();
		if (LOG_ENABLED) {
			Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
		}
		outVal.put(key, value);
		N--;
	}
}
 
Example 26
Project: exciting-app   File: AbsHListView.java   View source code 5 votes vote down vote up
private void writeSparseLongArray(LongSparseArray<Integer> array,
		Parcel out) {
	if (LOG_ENABLED) {
		Log.i(TAG, "writeSparseLongArray");
	}
	final int N = array != null ? array.size() : 0;
	out.writeInt(N);
	for (int i = 0; i < N; i++) {
		out.writeLong(array.keyAt(i));
		out.writeInt(array.valueAt(i));
	}
}
 
Example 27
Project: FlickLauncher   File: ImportDataTask.java   View source code 5 votes vote down vote up
public boolean importWorkspace() throws Exception {
    ArrayList<Long> allScreens = LauncherDbUtils.getScreenIdsFromCursor(
            mContext.getContentResolver().query(mOtherScreensUri, null, null, null,
                    LauncherSettings.WorkspaceScreens.SCREEN_RANK));

    // During import we reset the screen IDs to 0-indexed values.
    if (allScreens.isEmpty()) {
        // No thing to migrate
        return false;
    }

    mHotseatSize = mMaxGridSizeX = mMaxGridSizeY = 0;

    // Build screen update
    ArrayList<ContentProviderOperation> screenOps = new ArrayList<>();
    int count = allScreens.size();
    LongSparseArray<Long> screenIdMap = new LongSparseArray<>(count);
    for (int i = 0; i < count; i++) {
        ContentValues v = new ContentValues();
        v.put(LauncherSettings.WorkspaceScreens._ID, i);
        v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
        screenIdMap.put(allScreens.get(i), (long) i);
        screenOps.add(ContentProviderOperation.newInsert(
                LauncherSettings.WorkspaceScreens.CONTENT_URI).withValues(v).build());
    }
    mContext.getContentResolver().applyBatch(ProviderConfig.AUTHORITY, screenOps);
    importWorkspaceItems(allScreens.get(0), screenIdMap);

    GridSizeMigrationTask.markForMigration(mContext, mMaxGridSizeX, mMaxGridSizeY, mHotseatSize);

    // Create empty DB flag.
    LauncherSettings.Settings.call(mContext.getContentResolver(),
            LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG);
    return true;
}
 
Example 28
Project: lighthouse   File: Records.java   View source code 5 votes vote down vote up
protected Records(Parcel in) {
    int version = in.readInt();
    records = in.createTypedArrayList(Record.CREATOR);
    recordsMap = new LongSparseArray<>(records.size());
    for (Record record : records) {
        recordsMap.put(record.getId(), record);
    }
    unmodifiableRecords = Collections.unmodifiableList(records);
}
 
Example 29
Project: lighthouse   File: Podcasts.java   View source code 5 votes vote down vote up
protected Podcasts(Parcel in) {
    podcasts = in.createTypedArrayList(Podcast.CREATOR);
    podcastsMap = new LongSparseArray<>(podcasts.size());
    for (Podcast podcast : podcasts) {
        podcastsMap.put(podcast.getId(), podcast);
    }
    unmodifiablePodcasts = Collections.unmodifiableList(podcasts);
}
 
Example 30
Project: lighthouse   File: Podcasts.java   View source code 5 votes vote down vote up
public Podcasts(Collection<Podcast> collection) {
    int capacity = collection.size();
    podcasts = new ArrayList<>(capacity);
    unmodifiablePodcasts = Collections.unmodifiableList(podcasts);
    podcastsMap = new LongSparseArray<>(capacity);
    for (Podcast podcast : collection) {
        if (podcastsMap.get(podcast.getId()) == null) {
            podcasts.add(podcast);
            podcastsMap.put(podcast.getId(), podcast);
        }
    }
}
 
Example 31
Project: MessageOnTap_API   File: Session.java   View source code 5 votes vote down vote up
public Session(String packageName, Task data) { // For Core
    mPackageName = packageName;
    mUncompleted = new HashSet<>();
    mTasks = new LongSparseArray<>();
    mTasks.put(0L, data);
    lastTID = 0;
}
 
Example 32
Project: MessageOnTap_API   File: Session.java   View source code 5 votes vote down vote up
public Session(Task data) { // For plugin
    mUncompleted = new HashSet<>();
    mTasks = new LongSparseArray<>();
    mTasks.put(0L, data);
    mUncompleted.add(0L);
    lastTID = 0;
}
 
Example 33
Project: MessageOnTap_API   File: LongSparseArrayTypeAdapter.java   View source code 5 votes vote down vote up
@Override
public void write(JsonWriter jsonWriter, LongSparseArray<T> tLongSparseArray) throws IOException {
    if (tLongSparseArray == null) {
        jsonWriter.nullValue();
        return;
    }
    gson.toJson(gson.toJsonTree(tLongSparseArray, typeOfLongSparseArrayOfT), jsonWriter);
}
 
Example 34
Project: SimpleUILauncher   File: ImportDataTask.java   View source code 5 votes vote down vote up
public boolean importWorkspace() throws Exception {
    ArrayList<Long> allScreens = LauncherDbUtils.getScreenIdsFromCursor(
            mContext.getContentResolver().query(mOtherScreensUri, null, null, null,
                    LauncherSettings.WorkspaceScreens.SCREEN_RANK));

    // During import we reset the screen IDs to 0-indexed values.
    if (allScreens.isEmpty()) {
        // No thing to migrate
        return false;
    }

    mHotseatSize = mMaxGridSizeX = mMaxGridSizeY = 0;

    // Build screen update
    ArrayList<ContentProviderOperation> screenOps = new ArrayList<>();
    int count = allScreens.size();
    LongSparseArray<Long> screenIdMap = new LongSparseArray<>(count);
    for (int i = 0; i < count; i++) {
        ContentValues v = new ContentValues();
        v.put(LauncherSettings.WorkspaceScreens._ID, i);
        v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
        screenIdMap.put(allScreens.get(i), (long) i);
        screenOps.add(ContentProviderOperation.newInsert(
                LauncherSettings.WorkspaceScreens.CONTENT_URI).withValues(v).build());
    }
    mContext.getContentResolver().applyBatch(ProviderConfig.AUTHORITY, screenOps);
    importWorkspaceItems(allScreens.get(0), screenIdMap);

    GridSizeMigrationTask.markForMigration(mContext, mMaxGridSizeX, mMaxGridSizeY, mHotseatSize);

    // Create empty DB flag.
    LauncherSettings.Settings.call(mContext.getContentResolver(),
            LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG);
    return true;
}
 
Example 35
Project: android_packages_apps_tv   File: SeriesRecordingScheduler.java   View source code 5 votes vote down vote up
@Override
protected void onPostExecute(List<Program> programs) {
    if (DEBUG) Log.d(TAG, "onPostExecute: updating schedules with programs:" + programs);
    mScheduleTasks.remove(this);
    if (programs == null) {
        Log.e(TAG, "Creating schedules for series recording failed: "
                + getSeriesRecordings());
        return;
    }
    LongSparseArray<List<Program>> seriesProgramMap = pickOneProgramPerEpisode(
            getSeriesRecordings(), programs);
    for (SeriesRecording seriesRecording : getSeriesRecordings()) {
        // Check the series recording is still valid.
        SeriesRecording actualSeriesRecording = mDataManager.getSeriesRecording(
                seriesRecording.getId());
        if (actualSeriesRecording == null || actualSeriesRecording.isStopped()) {
            continue;
        }
        List<Program> programsToSchedule = seriesProgramMap.get(seriesRecording.getId());
        if (mDataManager.getSeriesRecording(seriesRecording.getId()) != null
                && !programsToSchedule.isEmpty()) {
            mDvrManager.addScheduleToSeriesRecording(seriesRecording, programsToSchedule);
        }
    }
    if (!mOnSeriesRecordingUpdatedListeners.isEmpty()) {
        for (OnSeriesRecordingUpdatedListener listener
                : mOnSeriesRecordingUpdatedListeners) {
            listener.onSeriesRecordingUpdated(
                    SeriesRecording.toArray(getSeriesRecordings()));
        }
    }
}
 
Example 36
Project: android_packages_apps_tv   File: SeriesRecordingSchedulerTest.java   View source code 5 votes vote down vote up
public void testPickOneProgramPerEpisode_onePerEpisode() {
    SeriesRecording seriesRecording = SeriesRecording.buildFrom(mBaseSeriesRecording)
            .setId(SERIES_RECORDING_ID1).build();
    mDataManager.addSeriesRecording(seriesRecording);
    List<Program> programs = new ArrayList<>();
    Program program1 = new Program.Builder(mBaseProgram).setSeasonNumber(SEASON_NUMBER1)
            .setEpisodeNumber(EPISODE_NUMBER1).build();
    programs.add(program1);
    Program program2 = new Program.Builder(mBaseProgram).setSeasonNumber(SEASON_NUMBER2)
            .setEpisodeNumber(EPISODE_NUMBER2).build();
    programs.add(program2);
    LongSparseArray<List<Program>> result = SeriesRecordingScheduler.pickOneProgramPerEpisode(
            mDataManager, Collections.singletonList(seriesRecording), programs);
    MoreAsserts.assertContentsInAnyOrder(result.get(SERIES_RECORDING_ID1), program1, program2);
}
 
Example 37
Project: android_packages_apps_tv   File: SeriesRecordingSchedulerTest.java   View source code 5 votes vote down vote up
public void testPickOneProgramPerEpisode_nullEpisode() {
    SeriesRecording seriesRecording = SeriesRecording.buildFrom(mBaseSeriesRecording)
            .setId(SERIES_RECORDING_ID1).build();
    mDataManager.addSeriesRecording(seriesRecording);
    List<Program> programs = new ArrayList<>();
    Program program1 = new Program.Builder(mBaseProgram).setStartTimeUtcMillis(0).build();
    programs.add(program1);
    Program program2 = new Program.Builder(mBaseProgram).setStartTimeUtcMillis(1).build();
    programs.add(program2);
    LongSparseArray<List<Program>> result = SeriesRecordingScheduler.pickOneProgramPerEpisode(
            mDataManager, Collections.singletonList(seriesRecording), programs);
    MoreAsserts.assertContentsInAnyOrder(result.get(SERIES_RECORDING_ID1), program1, program2);
}
 
Example 38
Project: SVG-Android   File: SVGHelper.java   View source code 5 votes vote down vote up
public static LongSparseArray<Drawable.ConstantState> hackPreloadDrawables(Resources res) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
        return hackPreloadDrawablesV15(res);
    } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR2) {
        return hackPreloadDrawablesV18(res);
    } else {
        return hackPreloadDrawablesV19(res);
    }
}
 
Example 39
Project: truth-android   File: LongSparseArraySubject.java   View source code 5 votes vote down vote up
public static SubjectFactory<LongSparseArraySubject, LongSparseArray> type() {
  return new SubjectFactory<LongSparseArraySubject, LongSparseArray>() {
    @Override
    public LongSparseArraySubject getSubject(FailureStrategy fs, LongSparseArray that) {
      return new LongSparseArraySubject(fs, that);
    }
  };
}
 
Example 40
Project: MediaMonkey   File: OnGoingSelectImpl.java   View source code 5 votes vote down vote up
@Override
public LongSparseArray<T> executeLongSparseArray(final Function<T, Long> keyFunction) {
    String sql = sqlSelect(klass, fieldExclusions, getConditions(), order, count, offset);
    final LongSparseArray<T> map = new LongSparseArray<>();
    forEachRow(getDatabase(), sql, klass, new Consumer<T>() {
        @Override
        public void accept(T value) {
            map.put(keyFunction.apply(value), value);
        }
    });
    return map;
}