Example usage for android.util SparseBooleanArray size

List of usage examples for android.util SparseBooleanArray size

Introduction

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

Prototype

public int size() 

Source Link

Document

Returns the number of key-value mappings that this SparseBooleanArray currently stores.

Usage

From source file:org.akop.crosswords.fragment.SubscriptionDetailFragment.java

private void saveCheckedItems() {
    int checkedCount = mListView.getCheckedItemCount();
    if (checkedCount > 0) {
        // Make a list of checked items
        PuzzleWrapper[] checkedItems = new PuzzleWrapper[checkedCount];
        SparseBooleanArray checked = mListView.getCheckedItemPositions();
        for (int i = 0, n = checked.size(), j = 0; i < n; i++) {
            if (checked.valueAt(i)) {
                checkedItems[j++] = mAdapter.getItem(checked.keyAt(i));
            }/*from   w w  w.  j av a 2 s . com*/
        }

        // Kick off the writer task
        WriterTask task = new WriterTask(false);
        task.execute(checkedItems);
    }
}

From source file:com.github.jvanhie.discogsscrobbler.NowPlayingFragment.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setSelection(final ListView list) {
    list.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
    list.setSelector(R.drawable.track_selector);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override/*from  w w  w .  j  av  a2  s  . c o m*/
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if (mBound) {
                //fully stop previous playlist since we start again from the beginning of the selected track
                ArrayList<Track> trackList = new ArrayList<Track>(mService.trackList);
                mService.stop();
                mService.trackList = trackList;
                mService.currentTrack = i;
                mService.resume();
            }
        }
    });
    list.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
        @Override
        public void onItemCheckedStateChanged(ActionMode actionMode, int i, long l, boolean b) {

        }

        @Override
        public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
            MenuInflater inflater = getActivity().getMenuInflater();
            inflater.inflate(R.menu.now_playing_cab, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            SparseBooleanArray checkedItems = list.getCheckedItemPositions();
            final List<Integer> positions = new ArrayList<Integer>();
            if (checkedItems != null) {
                for (int i = 0; i < checkedItems.size(); i++) {
                    if (checkedItems.valueAt(i)) {
                        positions.add(checkedItems.keyAt(i));
                    }
                }
            }
            switch (menuItem.getItemId()) {
            case R.id.play_selection:
                if (mBound) {
                    //change tracklist and start over again
                    ArrayList<Track> newTrackList = new ArrayList<Track>();
                    for (Integer i : positions) {
                        newTrackList.add(mService.trackList.get(i));
                    }
                    //fully stop previous playlist since we start again from the beginning
                    mService.stop();
                    mService.trackList = newTrackList;
                    mService.currentTrack = 0;
                    mService.resume();
                }
                actionMode.finish();
                break;
            case R.id.remove_selection:
                int currPlaying = mService.currentTrack;
                int newPlaying = -1;
                //change tracklist and start over again
                ArrayList<Track> newTrackList = new ArrayList<Track>();
                for (int i = 0; i < mService.trackList.size(); i++) {
                    if (!positions.contains(i)) {
                        newTrackList.add(mService.trackList.get(i));
                    }
                    //calculate new currently playing counter
                    if (i == currPlaying) {
                        if (positions.contains(i)) {
                            currPlaying++;
                        } else {
                            newPlaying = newTrackList.size() - 1;
                        }
                    }
                }
                //the currently playing track was removed, start fresh from the next available
                if (currPlaying != mService.currentTrack) {
                    mService.stop();
                    if (newPlaying != -1) {
                        mService.trackList = newTrackList;
                        mService.currentTrack = newPlaying;
                        mService.resume();
                    }
                } else {
                    //pause the playlist and resume with the new tracklist
                    mService.pause();
                    mService.trackList = newTrackList;
                    mService.currentTrack = newPlaying;
                    mService.resume();
                }
                actionMode.finish();
                break;
            }
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {

        }
    });
}

From source file:org.awesomeapp.messenger.ui.ContactsPickerActivity.java

private void multiFinish(SparseBooleanArray positions) {

    ArrayList<String> users = new ArrayList<String>();
    ArrayList<Integer> providers = new ArrayList<Integer>();
    ArrayList<Integer> accounts = new ArrayList<Integer>();

    for (int i = 0; i < positions.size(); i++) {
        if (positions.valueAt(i)) {
            Cursor cursor = (Cursor) mAdapter.getItem(i);

            users.add(cursor.getString(ContactListItem.COLUMN_CONTACT_USERNAME));
            providers.add((int) cursor.getLong(ContactListItem.COLUMN_CONTACT_PROVIDER));
            accounts.add((int) cursor.getLong(ContactListItem.COLUMN_CONTACT_ACCOUNT));
        }//from   w  w w.j ava2s . co  m
    }

    Intent data = new Intent();
    data.putStringArrayListExtra(EXTRA_RESULT_USERNAMES, users);
    data.putIntegerArrayListExtra(EXTRA_RESULT_PROVIDER, providers);
    data.putIntegerArrayListExtra(EXTRA_RESULT_ACCOUNT, accounts);
    setResult(RESULT_OK, data);
    finish();
}

From source file:org.totschnig.myexpenses.fragment.MethodList.java

@Override
public boolean dispatchCommandMultiple(int command, SparseBooleanArray positions, Long[] itemIds) {
    switch (command) {
    case R.id.DELETE_COMMAND:
        int columnIndexMappedTransactions = mMethodsCursor
                .getColumnIndex(DatabaseConstants.KEY_MAPPED_TRANSACTIONS);
        int columnIndexMappedTemplates = mMethodsCursor.getColumnIndex(DatabaseConstants.KEY_MAPPED_TEMPLATES);
        int columnIndexRowId = mMethodsCursor.getColumnIndex(DatabaseConstants.KEY_ROWID);
        int mappedTransactionsCount = 0, mappedTemplatesCount = 0;
        ArrayList<Long> idList = new ArrayList<>();
        for (int i = 0; i < positions.size(); i++) {
            if (positions.valueAt(i)) {
                boolean deletable = true;
                mMethodsCursor.moveToPosition(positions.keyAt(i));
                if (mMethodsCursor.getInt(columnIndexMappedTransactions) > 0) {
                    mappedTransactionsCount++;
                    deletable = false;//w  w  w  . ja v a 2 s . c  om
                }
                if (mMethodsCursor.getInt(columnIndexMappedTemplates) > 0) {
                    mappedTemplatesCount++;
                    deletable = false;
                }
                if (deletable) {
                    idList.add(mMethodsCursor.getLong(columnIndexRowId));
                }
            }
        }
        if (!idList.isEmpty()) {
            ((ProtectedFragmentActivity) getActivity()).startTaskExecution(
                    TaskExecutionFragment.TASK_DELETE_PAYMENT_METHODS, idList.toArray(new Long[idList.size()]),
                    null, R.string.progress_dialog_deleting);
            return true;
        }
        if (mappedTransactionsCount > 0 || mappedTemplatesCount > 0) {
            String message = "";
            if (mappedTransactionsCount > 0)
                message += getResources().getQuantityString(R.plurals.not_deletable_mapped_transactions,
                        mappedTransactionsCount, mappedTransactionsCount);
            if (mappedTemplatesCount > 0)
                message += getResources().getQuantityString(R.plurals.not_deletable_mapped_templates,
                        mappedTemplatesCount, mappedTemplatesCount);
            Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
        }
        break;
    }
    return super.dispatchCommandMultiple(command, positions, itemIds);
}

From source file:org.totschnig.myexpenses.fragment.PartiesList.java

@Override
public boolean dispatchCommandMultiple(int command, SparseBooleanArray positions, Long[] itemIds) {
    switch (command) {
    case R.id.DELETE_COMMAND:
        int columnIndexMappedTransactions = mPartiesCursor
                .getColumnIndex(DatabaseConstants.KEY_MAPPED_TRANSACTIONS);
        int columnIndexMappedTemplates = mPartiesCursor.getColumnIndex(DatabaseConstants.KEY_MAPPED_TEMPLATES);
        int columnIndexRowId = mPartiesCursor.getColumnIndex(DatabaseConstants.KEY_ROWID);
        int mappedTransactionsCount = 0, mappedTemplatesCount = 0;
        ArrayList<Long> idList = new ArrayList<>();
        for (int i = 0; i < positions.size(); i++) {
            if (positions.valueAt(i)) {
                boolean deletable = true;
                mPartiesCursor.moveToPosition(positions.keyAt(i));
                if (mPartiesCursor.getInt(columnIndexMappedTransactions) > 0) {
                    mappedTransactionsCount++;
                    deletable = false;/*from   www .  j a  v  a 2s. c om*/
                }
                if (mPartiesCursor.getInt(columnIndexMappedTemplates) > 0) {
                    mappedTemplatesCount++;
                    deletable = false;
                }
                if (deletable) {
                    idList.add(mPartiesCursor.getLong(columnIndexRowId));
                }
            }
        }
        if (!idList.isEmpty()) {
            ((ProtectedFragmentActivity) getActivity()).startTaskExecution(
                    TaskExecutionFragment.TASK_DELETE_PAYEES, idList.toArray(new Long[idList.size()]), null,
                    R.string.progress_dialog_deleting);
            return true;
        }
        if (mappedTransactionsCount > 0 || mappedTemplatesCount > 0) {
            String message = "";
            if (mappedTransactionsCount > 0)
                message += getResources().getQuantityString(R.plurals.not_deletable_mapped_transactions,
                        mappedTransactionsCount, mappedTransactionsCount);
            if (mappedTemplatesCount > 0)
                message += getResources().getQuantityString(R.plurals.not_deletable_mapped_templates,
                        mappedTemplatesCount, mappedTemplatesCount);
            Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
        }
        break;
    }
    return super.dispatchCommandMultiple(command, positions, itemIds);
}

From source file:de.qspool.clementineremote.ui.fragments.PlaylistFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_playlist, container, false);

    mPlaylists = mPlaylistManager.getAllPlaylists();

    mList = (ListView) view.findViewById(R.id.songs);
    mEmptyPlaylist = view.findViewById(R.id.playlist_empty);

    // Add Spinner to toolbar
    mPlaylistsSpinner = (Spinner) getActivity().findViewById(R.id.toolbar_spinner);

    mPlaylistsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override/*from  w ww.j av  a 2  s .  c o  m*/
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            updateSongList();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    updatePlaylistSpinner();

    // Create the adapter
    mAdapter = new PlaylistSongAdapter(getActivity(), R.layout.item_playlist, getSelectedPlaylistSongs());

    mList.setOnItemClickListener(oiclSong);
    mList.setAdapter(mAdapter);

    mList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    mList.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
        @Override
        public boolean onActionItemClicked(ActionMode mode, android.view.MenuItem item) {
            SparseBooleanArray checkedPositions = mList.getCheckedItemPositions();
            LinkedList<MySong> selectedSongs = new LinkedList<>();

            for (int i = 0; i < checkedPositions.size(); ++i) {
                int position = checkedPositions.keyAt(i);
                if (checkedPositions.valueAt(i)) {
                    selectedSongs.add(getSelectedPlaylistSongs().get(position));
                }
            }

            if (!selectedSongs.isEmpty()) {
                switch (item.getItemId()) {
                case R.id.playlist_context_play:
                    playSong(selectedSongs.get(0));

                    mode.finish();
                    return true;
                case R.id.playlist_context_download:
                    LinkedList<String> urls = new LinkedList<>();
                    for (MySong s : selectedSongs) {
                        urls.add(s.getUrl());
                    }
                    if (!urls.isEmpty()) {
                        DownloadManager.getInstance().addJob(
                                ClementineMessageFactory.buildDownloadSongsMessage(DownloadItem.Urls, urls));
                    }
                    mode.finish();
                    return true;
                case R.id.playlist_context_remove:
                    Message msg = Message.obtain();
                    msg.obj = ClementineMessageFactory.buildRemoveMultipleSongsFromPlaylist(getPlaylistId(),
                            selectedSongs);
                    App.ClementineConnection.mHandler.sendMessage(msg);
                    mode.finish();
                    return true;
                default:
                    return false;
                }
            }
            return false;
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, android.view.Menu menu) {
            android.view.MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.playlist_context_menu, menu);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                getActivity().getWindow()
                        .setStatusBarColor(ContextCompat.getColor(getActivity(), R.color.grey_cab_status));

            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, android.view.Menu menu) {
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                getActivity().getWindow()
                        .setStatusBarColor(ContextCompat.getColor(getActivity(), R.color.actionbar_dark));
        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
        }
    });

    // Filter the results
    mAdapter.getFilter().filter(mFilterText);

    mActionBar.setTitle("");
    mActionBar.setSubtitle("");

    return view;
}

From source file:com.gmail.taneza.ronald.carbs.main.MainActivity.java

private void deleteFromFoodList(ArrayList<FoodItem> foodList, SparseBooleanArray itemsToDelete) {
    int numItemsToDelete = itemsToDelete.size();
    if (itemsToDelete.size() <= 0) {
        return;//  w  ww.  ja v a 2s . c o  m
    }

    if (numItemsToDelete > foodList.size()) {
        throw new IllegalArgumentException("numItemsToDelete is larger than the foodList size");
    }

    // Each item in 'itemsToDelete' has a key and a value.
    // The key is an index to 'mFoodItemsList'.
    // The value is a boolean: true means that the item should be deleted.
    // Start from the end of the list, because items in the list will be shifted after each 'delete' call.
    // Keys are guaranteed to be sorted in ascending order,
    // e.g. keyAt(0) will return the smallest key and keyAt(size()-1) will return the largest key.
    for (int n = (numItemsToDelete - 1); n >= 0; n--) {
        int index = itemsToDelete.keyAt(n);
        if (itemsToDelete.get(index)) {
            foodList.remove(index);
        }
    }

    updateRecentFoodsAndMealData();
}

From source file:com.concentricsky.android.khanacademy.app.ManageDownloadsActivity.java

private void confirmAndDelete() {
    View contentView = getLayoutInflater().inflate(R.layout.dialog_confirm_delete, null, false);
    ListView list = (ListView) contentView.findViewById(R.id.dialog_confirm_delete_list);

    ArrayList<String> titles = new ArrayList<String>();
    final HashSet<Video> videos = new HashSet<Video>();

    SparseBooleanArray positions = gridView.getCheckedItemPositions();
    int n = positions.size();
    for (int i = 0; i < n; ++i) {
        Cursor c = (Cursor) gridView.getItemAtPosition(positions.keyAt(i));
        Video v = new Video();
        v.setReadable_id(c.getString(c.getColumnIndex("readable_id")));
        v.setYoutube_id(c.getString(c.getColumnIndex("youtube_id")));
        v.setDlm_id(c.getLong(c.getColumnIndex("dlm_id")));
        videos.add(v);/* w  w  w.j  av  a2  s .  c om*/
        titles.add(c.getString(c.getColumnIndex("title")));
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.dialog_confirm_delete_item);
    adapter.addAll(titles);
    list.setAdapter(adapter);

    new AlertDialog.Builder(this).setView(contentView).setMessage(getString(R.string.msg_delete_videos))
            .setPositiveButton(getString(R.string.button_confirm_delete),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            deleteItems(videos);
                            if (actionMode != null) {
                                actionMode.finish();
                            }
                        }
                    })
            .setNegativeButton(getString(R.string.button_cancel), null).show();
}

From source file:com.rc.droid_stalker.components.NetworkStats.java

/**
 * Return list of unique UIDs known by this data structure.
 *///from  ww  w . j  a  v  a 2  s  . co  m
public int[] getUniqueUids() {
    final SparseBooleanArray uids = new SparseBooleanArray();
    for (int uid : this.uid) {
        uids.put(uid, true);
    }

    final int size = uids.size();
    final int[] result = new int[size];
    for (int i = 0; i < size; i++) {
        result[i] = uids.keyAt(i);
    }
    return result;
}

From source file:org.mariotaku.twidere.fragment.AddStatusFilterDialogFragment.java

@NonNull
@Override//from   w  w w  . ja  v  a2s  . com
public Dialog onCreateDialog(final Bundle savedInstanceState) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    mFilterItems = getFilterItemsInfo();
    final String[] entries = new String[mFilterItems.length];
    final boolean nameFirst = mPreferences.getBoolean(KEY_NAME_FIRST);
    for (int i = 0, j = entries.length; i < j; i++) {
        final FilterItemInfo info = mFilterItems[i];
        switch (info.type) {
        case FilterItemInfo.FILTER_TYPE_USER:
            entries[i] = getString(R.string.user_filter_name,
                    getName(mUserColorNameManager, info.value, nameFirst));
            break;
        case FilterItemInfo.FILTER_TYPE_KEYWORD:
            entries[i] = getString(R.string.keyword_filter_name,
                    getName(mUserColorNameManager, info.value, nameFirst));
            break;
        case FilterItemInfo.FILTER_TYPE_SOURCE:
            entries[i] = getString(R.string.source_filter_name,
                    getName(mUserColorNameManager, info.value, nameFirst));
            break;
        }
    }
    builder.setTitle(R.string.add_to_filter);
    builder.setMultiChoiceItems(entries, null, null);
    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            AlertDialog alertDialog = ((AlertDialog) dialog);
            final SparseBooleanArray checkPositions = alertDialog.getListView().getCheckedItemPositions();

            final Set<UserKey> userKeys = new HashSet<>();
            final Set<String> keywords = new HashSet<>();
            final Set<String> sources = new HashSet<>();
            final ArrayList<ContentValues> userValues = new ArrayList<>();
            final ArrayList<ContentValues> keywordValues = new ArrayList<>();
            final ArrayList<ContentValues> sourceValues = new ArrayList<>();
            for (int i = 0, j = checkPositions.size(); i < j; i++) {
                if (!checkPositions.valueAt(i))
                    continue;
                final FilterItemInfo info = mFilterItems[checkPositions.keyAt(i)];
                final Object value = info.value;
                if (value instanceof ParcelableUserMention) {
                    final ParcelableUserMention mention = (ParcelableUserMention) value;
                    userKeys.add(mention.key);
                    userValues.add(ContentValuesCreator.createFilteredUser(mention));
                } else if (value instanceof UserItem) {
                    final UserItem item = (UserItem) value;
                    userKeys.add(item.key);
                    userValues.add(createFilteredUser(item));
                } else if (info.type == FilterItemInfo.FILTER_TYPE_KEYWORD) {
                    if (value != null) {
                        final String keyword = ParseUtils.parseString(value);
                        keywords.add(keyword);
                        final ContentValues values = new ContentValues();
                        values.put(Filters.Keywords.VALUE, "#" + keyword);
                        keywordValues.add(values);
                    }
                } else if (info.type == FilterItemInfo.FILTER_TYPE_SOURCE) {
                    if (value != null) {
                        final String source = ParseUtils.parseString(value);
                        sources.add(source);
                        final ContentValues values = new ContentValues();
                        values.put(Filters.Sources.VALUE, source);
                        sourceValues.add(values);
                    }
                }
            }
            final ContentResolver resolver = getContentResolver();
            ContentResolverUtils.bulkDelete(resolver, Filters.Users.CONTENT_URI, Filters.Users.USER_KEY,
                    userKeys, null);
            ContentResolverUtils.bulkDelete(resolver, Filters.Keywords.CONTENT_URI, Filters.Keywords.VALUE,
                    keywords, null);
            ContentResolverUtils.bulkDelete(resolver, Filters.Sources.CONTENT_URI, Filters.Sources.VALUE,
                    sources, null);
            ContentResolverUtils.bulkInsert(resolver, Filters.Users.CONTENT_URI, userValues);
            ContentResolverUtils.bulkInsert(resolver, Filters.Keywords.CONTENT_URI, keywordValues);
            ContentResolverUtils.bulkInsert(resolver, Filters.Sources.CONTENT_URI, sourceValues);
        }
    });
    builder.setNegativeButton(android.R.string.cancel, null);
    return builder.create();
}