Example usage for android.util SparseBooleanArray valueAt

List of usage examples for android.util SparseBooleanArray valueAt

Introduction

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

Prototype

public boolean valueAt(int index) 

Source Link

Document

Given an index in the range 0...size()-1, returns the value from the indexth key-value mapping that this SparseBooleanArray stores.

Usage

From source file:org.tigase.mobile.bookmarks.BookmarksActivity.java

@TargetApi(11)
private void initializeContextActions() {

    listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
    listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

        private Bookmark getBookmarkFromFlatPosition(int pos) {
            long packed = listView.getExpandableListPosition(pos);
            int child = ExpandableListView.getPackedPositionChild(packed);
            int group = ExpandableListView.getPackedPositionGroup(packed);

            return (Bookmark) adapter.getChild(group, child);
        }//from w w  w  .java2  s .  c  o m

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            SparseBooleanArray selection = listView.getCheckedItemPositions();

            if (item.getItemId() == R.id.edit) {
                for (int i = 0; i < selection.size(); i++) {
                    if (selection.valueAt(i)) {
                        int pos = selection.keyAt(i);

                        Bookmark bookmark = getBookmarkFromFlatPosition(pos);
                        editItem(bookmark);
                    }
                }
                mode.finish(); // Action picked, so close the CAB
                return true;
            } else if (item.getItemId() == R.id.remove) {
                List<Bookmark> items = new ArrayList<Bookmark>();
                for (int i = 0; i < selection.size(); i++) {
                    if (selection.valueAt(i)) {
                        int pos = selection.keyAt(i);

                        Bookmark bookmark = getBookmarkFromFlatPosition(pos);
                        if (bookmark != null) {
                            items.add(bookmark);
                        }
                    }
                }
                removeItems(items);
                mode.finish();
                return true;
            } else {
                return false;
            }

        }

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

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            Menu menu = mode.getMenu();
            for (int i = 0; i < menu.size(); i++) {
                MenuItem mi = menu.getItem(i);
                if (mi.getItemId() == R.id.edit) {
                    mi.setVisible(listView.getCheckedItemCount() < 2);
                }
            }
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // TODO Auto-generated method stub
            return true;
        }

    });
}

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. ja  v a 2  s . c o  m*/
        }

        // 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//  ww w. j  a v  a 2s  .  co  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.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;/*from ww w.j av a2 s . c  o m*/
                }
                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   ww  w  .j  a  v  a 2  s  .  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:com.btmura.android.reddit.app.NavigationFragment.java

private String[] getCheckedSubreddits() {
    ListView lv = getListView();/*from w w w.  j av a  2 s .  co m*/
    SparseBooleanArray checked = lv.getCheckedItemPositions();
    String[] subreddits = new String[lv.getCheckedItemCount()];

    int size = checked.size();
    int j = 0;
    for (int i = 0; i < size; i++) {
        if (checked.valueAt(i)) {
            int position = checked.keyAt(i);
            int adapterPosition = mergeAdapter.getAdapterPosition(position);
            subreddits[j++] = subredditAdapter.getName(adapterPosition);
        }
    }

    return subreddits;
}

From source file:com.android.contacts.SimImportFragment.java

private void importCurrentSelections() {
    final SparseBooleanArray checked = mListView.getCheckedItemPositions();
    final ArrayList<SimContact> importableContacts = new ArrayList<>(checked.size());
    for (int i = 0; i < checked.size(); i++) {
        // It's possible for existing contacts to be "checked" but we only want to import the
        // ones that don't already exist
        if (checked.valueAt(i) && !mAdapter.existsInCurrentAccount(i)) {
            importableContacts.add(mAdapter.getItem(checked.keyAt(i)));
        }/* www. j a v a 2s.c om*/
    }
    SimImportService.startImport(getContext(), mSubscriptionId, importableContacts,
            mAccountHeaderPresenter.getCurrentAccount());
}

From source file:com.serenegiant.aceparrot.MediaFragment.java

/**
 * ???/*from  w  w  w.  j a  v  a 2s  . c  o  m*/
 * @return
 */
private ARMediaObject[] getSelectedMedias() {
    ARMediaObject[] result = null;
    if (mMediaListView != null) {
        final SparseBooleanArray ids = mMediaListView.getCheckedItemPositions();
        final int n = ids != null ? ids.size() : 0;
        if (n > 0) {
            final List<ARMediaObject> list = new ArrayList<ARMediaObject>();
            for (int i = 0; i < n; i++) {
                if (ids.valueAt(i)) {
                    final Object obj = mMediaListView.getItemAtPosition(ids.keyAt(i));
                    if (obj instanceof ARMediaObject) {
                        list.add((ARMediaObject) obj);
                    }
                }
            }
            final int m = list.size();
            if (m > 0) {
                result = new ARMediaObject[m];
                list.toArray(result);
            }
        }
    }
    return result;
}

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/* w w  w.  j  a  v a  2s.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:org.mariotaku.twidere.fragment.AddStatusFilterDialogFragment.java

@NonNull
@Override//from  w  w w  .java2s .c  o m
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();
}