List of usage examples for android.database Cursor moveToPosition
boolean moveToPosition(int position);
From source file:org.totschnig.myexpenses.fragment.CategoryList.java
@Override public boolean dispatchCommandMultiple(int command, SparseBooleanArray positions, Long[] itemIds) { ManageCategories ctx = (ManageCategories) getActivity(); ArrayList<Long> idList; switch (command) { case R.id.DELETE_COMMAND: int mappedTransactionsCount = 0, mappedTemplatesCount = 0, hasChildrenCount = 0; idList = new ArrayList<>(); for (int i = 0; i < positions.size(); i++) { Cursor c; if (positions.valueAt(i)) { boolean deletable = true; int position = positions.keyAt(i); long pos = mListView.getExpandableListPosition(position); int type = ExpandableListView.getPackedPositionType(pos); int group = ExpandableListView.getPackedPositionGroup(pos), child = ExpandableListView.getPackedPositionChild(pos); if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) { c = mAdapter.getChild(group, child); c.moveToPosition(child); } else { c = mGroupCursor;/*from ww w .ja va 2 s.c o m*/ c.moveToPosition(group); } long itemId = c.getLong(c.getColumnIndex(KEY_ROWID)); Bundle extras = ctx.getIntent().getExtras(); if ((extras != null && extras.getLong(KEY_ROWID) == itemId) || c.getInt(c.getColumnIndex(DatabaseConstants.KEY_MAPPED_TRANSACTIONS)) > 0) { mappedTransactionsCount++; deletable = false; } else if (c.getInt(c.getColumnIndex(DatabaseConstants.KEY_MAPPED_TEMPLATES)) > 0) { mappedTemplatesCount++; deletable = false; } if (deletable) { if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP && c.getInt(c.getColumnIndex(KEY_CHILD_COUNT)) > 0) { hasChildrenCount++; } idList.add(itemId); } } } if (!idList.isEmpty()) { Long[] objectIds = idList.toArray(new Long[idList.size()]); if (hasChildrenCount > 0) { MessageDialogFragment .newInstance(R.string.dialog_title_warning_delete_main_category, getResources().getQuantityString(R.plurals.warning_delete_main_category, hasChildrenCount, hasChildrenCount), new MessageDialogFragment.Button(android.R.string.yes, R.id.DELETE_COMMAND_DO, objectIds), null, new MessageDialogFragment.Button(android.R.string.no, R.id.CANCEL_CALLBACK_COMMAND, null)) .show(ctx.getSupportFragmentManager(), "DELETE_CATEGORY"); } else { ctx.dispatchCommand(R.id.DELETE_COMMAND_DO, objectIds); } } 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(); } return true; case R.id.SELECT_COMMAND_MULTIPLE: ArrayList<String> labelList = new ArrayList<>(); for (int i = 0; i < positions.size(); i++) { Cursor c; if (positions.valueAt(i)) { int position = positions.keyAt(i); long pos = mListView.getExpandableListPosition(position); int type = ExpandableListView.getPackedPositionType(pos); int group = ExpandableListView.getPackedPositionGroup(pos), child = ExpandableListView.getPackedPositionChild(pos); if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) { c = mAdapter.getChild(group, child); c.moveToPosition(child); } else { c = mGroupCursor; c.moveToPosition(group); } labelList.add(c.getString(c.getColumnIndex(KEY_LABEL))); } } Intent intent = new Intent(); intent.putExtra(KEY_CATID, ArrayUtils.toPrimitive(itemIds)); intent.putExtra(KEY_LABEL, TextUtils.join(",", labelList)); ctx.setResult(ManageCategories.RESULT_FIRST_USER, intent); ctx.finish(); return true; case R.id.MOVE_COMMAND: final Long[] excludedIds; final boolean inGroup = expandableListSelectionType == ExpandableListView.PACKED_POSITION_TYPE_GROUP; if (inGroup) { excludedIds = itemIds; } else { idList = new ArrayList<>(); for (int i = 0; i < positions.size(); i++) { if (positions.valueAt(i)) { int position = positions.keyAt(i); long pos = mListView.getExpandableListPosition(position); int group = ExpandableListView.getPackedPositionGroup(pos); mGroupCursor.moveToPosition(group); idList.add(mGroupCursor.getLong(mGroupCursor.getColumnIndex(KEY_ROWID))); } } excludedIds = idList.toArray(new Long[idList.size()]); } Bundle args = new Bundle(3); args.putBoolean(SelectMainCategoryDialogFragment.KEY_WITH_ROOT, !inGroup); args.putLongArray(SelectMainCategoryDialogFragment.KEY_EXCLUDED_ID, ArrayUtils.toPrimitive(excludedIds)); args.putLongArray(TaskExecutionFragment.KEY_OBJECT_IDS, ArrayUtils.toPrimitive(itemIds)); SelectMainCategoryDialogFragment.newInstance(args).show(getFragmentManager(), "SELECT_TARGET"); return true; } return false; }
From source file:com.dsdar.thosearoundme.util.ContactsListFragment.java
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // This swaps the new cursor into the adapter. if (loader.getId() == ContactsQuery.QUERY_ID) { mAdapter.swapCursor(data);//w w w .j a va2s . co m // If this is a two-pane layout and there is a search query then // there is some additional work to do around default selected // search item. if (mIsTwoPaneLayout && !TextUtils.isEmpty(mSearchTerm) && mSearchQueryChanged) { // Selects the first item in results, unless this fragment has // been restored from a saved state (like orientation change) // in which case it selects the previously selected search item. if (data != null && data.moveToPosition(mPreviouslySelectedSearchItem)) { // Creates the content Uri for the previously selected // contact by appending the // contact's ID to the Contacts table content Uri final Uri uri = Uri.withAppendedPath(Contacts.CONTENT_URI, String.valueOf(data.getLong(ContactsQuery.ID))); mOnContactSelectedListener.onContactSelected(uri); getListView().setItemChecked(mPreviouslySelectedSearchItem, true); } else { // No results, clear selection. onSelectionCleared(); } // Only restore from saved state one time. Next time fall back // to selecting first item. If the fragment state is saved again // then the currently selected item will once again be saved. mPreviouslySelectedSearchItem = 0; mSearchQueryChanged = false; } } }
From source file:com.example.navigationsearchview.NavigationSearchView.java
/** * Query rewriting.//from w w w. j a v a2 s . c o m */ private void rewriteQueryFromSuggestion(int position) { CharSequence oldQuery = mSearchSrcTextView.getText(); Cursor c = mSuggestionsAdapter.getCursor(); if (c == null) { return; } if (c.moveToPosition(position)) { // Get the new query from the suggestion. CharSequence newQuery = mSuggestionsAdapter.convertToString(c); if (newQuery != null) { // The suggestion rewrites the query. // Update the text field, without getting new suggestions. setQuery(newQuery); } else { // The suggestion does not rewrite the query, restore the user's // query. setQuery(oldQuery); } } else { // We got a bad position, restore the user's query. setQuery(oldQuery); } }
From source file:com.android.calendar.event.EditEventView.java
private int findSelectedCalendarPosition(Cursor calendarsCursor, long calendarId) { if (calendarsCursor.getCount() <= 0) { return -1; }/*w ww .java 2 s .c om*/ int calendarIdColumn = calendarsCursor.getColumnIndexOrThrow(Calendars._ID); int position = 0; calendarsCursor.moveToPosition(-1); while (calendarsCursor.moveToNext()) { if (calendarsCursor.getLong(calendarIdColumn) == calendarId) { return position; } position++; } return 0; }
From source file:mp.teardrop.SongTimeline.java
/** * Run the given query and add the results to the song timeline. * * @param context A context to use.//from w ww . j a v a 2 s. c o m * @param query The query to be run. The mode variable must be initialized * to one of SongTimeline.MODE_*. The type and data variables may also need * to be initialized depending on the given mode. * @return The number of songs that were added. */ public int addSongs(Context context, QueryTask query) { Cursor cursor = query.runQuery(context.getContentResolver()); if (cursor == null) { return 0; } int count = cursor.getCount(); if (count == 0) { return 0; } int mode = query.mode; int type = query.type; long data = query.data; ArrayList<Song> timeline = mSongs; synchronized (this) { saveActiveSongs(); switch (mode) { case MODE_ENQUEUE: case MODE_ENQUEUE_POS_FIRST: case MODE_ENQUEUE_ID_FIRST: break; case MODE_PLAY_NEXT: timeline.subList(mCurrentPos + 1, timeline.size()).clear(); break; case MODE_PLAY: case MODE_PLAY_POS_FIRST: case MODE_PLAY_ID_FIRST: timeline.clear(); mCurrentPos = 0; break; default: throw new IllegalArgumentException("Invalid mode: " + mode); } int start = timeline.size(); Song jumpSong = null; for (int j = 0; j != count; ++j) { cursor.moveToPosition(j); Song song = new Song(-1); song.populate(cursor); timeline.add(song); if (jumpSong == null) { if ((mode == MODE_PLAY_POS_FIRST || mode == MODE_ENQUEUE_POS_FIRST) && j == data) { jumpSong = song; } else if (mode == MODE_PLAY_ID_FIRST || mode == MODE_ENQUEUE_ID_FIRST) { long id; switch (type) { /* case MediaUtils.TYPE_ARTIST: id = song.artistId; break; case MediaUtils.TYPE_ALBUM: id = song.albumId; break; case MediaUtils.TYPE_SONG: id = song.id; break; */ default: throw new IllegalArgumentException("Unsupported id type: " + type); } /* if (id == data) jumpSong = song; */ } } } if (mShuffleMode != SHUFFLE_NONE) MediaUtils.shuffle(timeline.subList(start, timeline.size()), mShuffleMode == SHUFFLE_ALBUMS); if (jumpSong != null) { int jumpPos = timeline.indexOf(jumpSong); if (jumpPos != start) { // Get the sublist twice to avoid a ConcurrentModificationException. timeline.addAll(timeline.subList(start, jumpPos)); timeline.subList(start, jumpPos).clear(); } } broadcastChangedSongs(); } changed(); return count; }
From source file:com.gimranov.zandy.app.ItemActivity.java
/** * Called when the activity is first created. *///from w w w . j a v a 2 s . c o m @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String persistedSort = Persistence.read(SORT_CHOICE); if (persistedSort != null) sortBy = persistedSort; db = new Database(this); setContentView(R.layout.items); Intent intent = getIntent(); collectionKey = intent.getStringExtra("com.gimranov.zandy.app.collectionKey"); ItemCollection coll = ItemCollection.load(collectionKey, db); APIRequest req; if (coll != null) { req = APIRequest.fetchItems(coll, false, new ServerCredentials(this)); } else { req = APIRequest.fetchItems(false, new ServerCredentials(this)); } prepareAdapter(); ItemAdapter adapter = (ItemAdapter) getListAdapter(); Cursor cur = adapter.getCursor(); if (intent.getBooleanExtra("com.gimranov.zandy.app.rerequest", false) || cur == null || cur.getCount() == 0) { if (!ServerCredentials.check(getBaseContext())) { Toast.makeText(getBaseContext(), getResources().getString(R.string.sync_log_in_first), Toast.LENGTH_SHORT).show(); return; } Toast.makeText(this, getResources().getString(R.string.collection_empty), Toast.LENGTH_SHORT).show(); Log.d(TAG, "Running a request to populate missing items"); ZoteroAPITask task = new ZoteroAPITask(this); req.setHandler(mEvent); task.execute(req); } ListView lv = getListView(); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // If we have a click on an item, do something... ItemAdapter adapter = (ItemAdapter) parent.getAdapter(); Cursor cur = adapter.getCursor(); // Place the cursor at the selected item if (cur.moveToPosition(position)) { // and load an activity for the item Item item = Item.load(cur); Log.d(TAG, "Loading item data with key: " + item.getKey()); // We create and issue a specified intent with the necessary data Intent i = new Intent(getBaseContext(), ItemDataActivity.class); i.putExtra("com.gimranov.zandy.app.itemKey", item.getKey()); i.putExtra("com.gimranov.zandy.app.itemDbId", item.dbId); startActivity(i); } else { // failed to move cursor-- show a toast TextView tvTitle = (TextView) view.findViewById(R.id.item_title); Toast.makeText(getApplicationContext(), getResources().getString(R.string.cant_open_item, tvTitle.getText()), Toast.LENGTH_SHORT).show(); } } }); }
From source file:com.android.contacts.ContactSaveService.java
/** * Gets the raw contact ids associated with {@param contactId}. * @param contactId/*from www .ja va 2 s . c om*/ * @return Array of raw contact ids. */ private long[] getRawContactIds(long contactId) { final ContentResolver resolver = getContentResolver(); long rawContactIds[]; final StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append(RawContacts.CONTACT_ID).append("=").append(String.valueOf(contactId)); final Cursor c = resolver.query(RawContacts.CONTENT_URI, JoinContactQuery.PROJECTION, queryBuilder.toString(), null, null); if (c == null) { Log.e(TAG, "Unable to open Contacts DB cursor"); return null; } try { rawContactIds = new long[c.getCount()]; for (int i = 0; i < rawContactIds.length; i++) { c.moveToPosition(i); final long rawContactId = c.getLong(JoinContactQuery._ID); rawContactIds[i] = rawContactId; } } finally { c.close(); } return rawContactIds; }
From source file:com.android.email.provider.EmailMessageCursor.java
public EmailMessageCursor(final Context c, final Cursor cursor, final String htmlColumn, final String textColumn) { super(cursor); mHtmlColumnIndex = cursor.getColumnIndex(htmlColumn); mTextColumnIndex = cursor.getColumnIndex(textColumn); final int cursorSize = cursor.getCount(); mHtmlParts = new SparseArray<String>(cursorSize); mTextParts = new SparseArray<String>(cursorSize); final ContentResolver cr = c.getContentResolver(); while (cursor.moveToNext()) { final int position = cursor.getPosition(); final long messageId = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID)); try {// w ww .j a va 2 s . c om if (mHtmlColumnIndex != -1) { final Uri htmlUri = Body.getBodyHtmlUriForMessageWithId(messageId); final InputStream in = cr.openInputStream(htmlUri); final String underlyingHtmlString; try { underlyingHtmlString = IOUtils.toString(in); } finally { in.close(); } final String sanitizedHtml = HtmlSanitizer.sanitizeHtml(underlyingHtmlString); mHtmlParts.put(position, sanitizedHtml); } } catch (final IOException e) { LogUtils.v(LogUtils.TAG, e, "Did not find html body for message %d", messageId); } try { if (mTextColumnIndex != -1) { final Uri textUri = Body.getBodyTextUriForMessageWithId(messageId); final InputStream in = cr.openInputStream(textUri); final String underlyingTextString; try { underlyingTextString = IOUtils.toString(in); } finally { in.close(); } mTextParts.put(position, underlyingTextString); } } catch (final IOException e) { LogUtils.v(LogUtils.TAG, e, "Did not find text body for message %d", messageId); } } cursor.moveToPosition(-1); }
From source file:info.guardianproject.otr.app.im.app.NewChatActivity.java
IChatSession getCurrentChatSession() { int currentPos = mChatPager.getCurrentItem(); if (currentPos == 0) return null; Cursor cursorChats = mChatPagerAdapter.getCursor(); cursorChats.moveToPosition(currentPos - 1); long providerId = cursorChats.getLong(ChatView.PROVIDER_COLUMN); String username = cursorChats.getString(ChatView.USERNAME_COLUMN); IChatSessionManager sessionMgr = getChatSessionManager(providerId); if (sessionMgr != null) { try {//from w w w.j a v a 2 s .c om IChatSession session = sessionMgr.getChatSession(username); if (session == null) session = sessionMgr.createChatSession(username, false); return session; } catch (RemoteException e) { mHandler.showServiceErrorAlert(e.getLocalizedMessage()); LogCleaner.error(ImApp.LOG_TAG, "send message error", e); } } return null; }
From source file:com.android.calendar.event.EditEventView.java
private int findDefaultCalendarPosition(Cursor calendarsCursor) { if (calendarsCursor.getCount() <= 0) { return -1; }//w w w . ja v a 2s . c o m String defaultCalendar = Utils.getSharedPreference(mActivity, GeneralPreferences.KEY_DEFAULT_CALENDAR, (String) null); int calendarsOwnerIndex = calendarsCursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT); int accountNameIndex = calendarsCursor.getColumnIndexOrThrow(Calendars.ACCOUNT_NAME); int accountTypeIndex = calendarsCursor.getColumnIndexOrThrow(Calendars.ACCOUNT_TYPE); int position = 0; calendarsCursor.moveToPosition(-1); while (calendarsCursor.moveToNext()) { String calendarOwner = calendarsCursor.getString(calendarsOwnerIndex); if (defaultCalendar == null) { // There is no stored default upon the first time running. Use a // primary // calendar in this case. if (calendarOwner != null && calendarOwner.equals(calendarsCursor.getString(accountNameIndex)) && !CalendarContract.ACCOUNT_TYPE_LOCAL .equals(calendarsCursor.getString(accountTypeIndex))) { return position; } } else if (defaultCalendar.equals(calendarOwner)) { // Found the default calendar. return position; } position++; } return 0; }