Example usage for android.database Cursor moveToPosition

List of usage examples for android.database Cursor moveToPosition

Introduction

In this page you can find the example usage for android.database Cursor moveToPosition.

Prototype

boolean moveToPosition(int position);

Source Link

Document

Move the cursor to an absolute position.

Usage

From source file:com.android.mail.ui.ActionBarController.java

@Override
public boolean onSuggestionClick(int position) {
    final Cursor c = mSearchWidget.getSuggestionsAdapter().getCursor();
    final boolean haveValidQuery = (c != null) && c.moveToPosition(position);
    if (!haveValidQuery) {
        LogUtils.d(LOG_TAG, "onSuggestionClick: Couldn't get a search query");
        // We haven't handled this query, but the default behavior will
        // leave EXTRA_ACCOUNT un-populated, leading to a crash. So claim
        // that we have handled the event.
        return true;
    }//from w ww .j  a v  a2s  .c  o  m
    collapseSearch();
    // what is in the text field
    String queryText = mSearchWidget.getQuery().toString();
    // What the suggested query is
    String query = c.getString(c.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1));
    // If the text the user typed in is a prefix of what is in the search
    // widget suggestion query, just take the search widget suggestion
    // query. Otherwise, it is a suffix and we want to remove matching
    // prefix portions.
    if (!TextUtils.isEmpty(queryText) && query.indexOf(queryText) != 0) {
        final int queryTokenIndex = queryText
                .lastIndexOf(SearchRecentSuggestionsProvider.QUERY_TOKEN_SEPARATOR);
        if (queryTokenIndex > -1) {
            queryText = queryText.substring(0, queryTokenIndex);
        }
        // Since we auto-complete on each token in a query, if the query the
        // user typed up until the last token is a substring of the
        // suggestion they click, make sure we don't double include the
        // query text. For example:
        // user types john, that matches john palo alto
        // User types john p, that matches john john palo alto
        // Remove the first john
        // Only do this if we have multiple query tokens.
        if (queryTokenIndex > -1 && !TextUtils.isEmpty(query) && query.contains(queryText)
                && queryText.length() < query.length()) {
            int start = query.indexOf(queryText);
            query = query.substring(0, start) + query.substring(start + queryText.length());
        }
    }
    mController.executeSearch(query.trim());
    return true;
}

From source file:au.com.cybersearch2.classyfy.ClassyfyLogic.java

/**
 * Perform content provider query for fast text search, Must be executed on background thread. 
 * @param searchQuery Query string/* ww w  .ja  v  a 2  s . c o  m*/
 * @return
 */
public List<ListItem> doSearchQuery(String searchQuery) {
    // Perform the search, passing in the search query as an argument to the Cursor Loader
    SuggestionCursorParameters params = new SuggestionCursorParameters(searchQuery,
            ClassyFySearchEngine.LEX_CONTENT_URI, ClassyFyProvider.SEARCH_RESULTS_LIMIT);

    ContentResolver contentResolver = context.getContentResolver();
    Cursor cursor = contentResolver.query(params.getUri(), params.getProjection(), params.getSelection(),
            params.getSelectionArgs(), params.getSortOrder());
    List<ListItem> fieldList = new ArrayList<ListItem>();
    int nameColumnId = cursor.getColumnIndexOrThrow(SearchManager.SUGGEST_COLUMN_TEXT_1);
    int valueColumnId = cursor.getColumnIndexOrThrow(SearchManager.SUGGEST_COLUMN_TEXT_2);
    // Id column name set in android.support.v4.widget.CursorAdaptor
    int idColumnId = cursor.getColumnIndexOrThrow("_id");
    if (cursor.getCount() > 0) {
        cursor.moveToPosition(-1);
        while (cursor.moveToNext()) {
            String name = cursor.getString(nameColumnId);
            String value = cursor.getString(valueColumnId);
            long id = cursor.getLong(idColumnId);
            fieldList.add(new ListItem(name, value, id));
        }
    }
    cursor.close();
    return fieldList;
}

From source file:de.fahrgemeinschaft.RideDetailsFragment.java

private void updateOptionsMenu() {
    Cursor cursor = getCursor();
    if (cursor != null && cursor.getCount() >= selected && edit != null && getActivity() != null) {
        cursor.moveToPosition(selected);
        if (isMyRide(cursor)) {
            edit.setVisible(true);//from w w  w  . j ava2 s  . co  m
            delete.setVisible(true);
            duplicate.setVisible(true);
            duplicate_retour.setVisible(true);
            toggle_active.setVisible(true);
            if (cursor.getInt(COLUMNS.ACTIVE) == 1) {
                toggle_active.setTitle(R.string.deactivate);
            } else {
                toggle_active.setTitle(R.string.activate);
            }
        } else {
            edit.setVisible(false);
            delete.setVisible(false);
            duplicate.setVisible(false);
            duplicate_retour.setVisible(false);
            toggle_active.setVisible(false);
        }
    }
}

From source file:org.wheelmap.android.activity.MainSinglePaneActivity.java

public void resetKategorieFilter() {
    Uri mUri = Support.CategoriesContent.CONTENT_URI;
    Cursor c = getContentResolver().query(mUri, Support.CategoriesContent.PROJECTION, null, null,
            Support.CategoriesContent.DEFAULT_SORT_ORDER);

    for (int i = 0; i < c.getCount(); i++) {
        c.moveToPosition(i);
        int catId = Support.CategoriesContent.getCategoryId(c);

        ContentResolver resolver = getContentResolver();
        ContentValues values = new ContentValues();
        values.put(Support.CategoriesContent.SELECTED, Support.CategoriesContent.SELECTED_YES);

        String whereClause = "( " + Support.CategoriesContent.CATEGORY_ID + " = ?)";
        String[] whereValues = new String[] { Integer.toString(catId) };
        resolver.update(mUri, values, whereClause, whereValues);
    }/*from   w  ww . j av  a 2s. c  o m*/
    c.close();
}

From source file:com.dycode.jepretstory.mediachooser.fragment.ImageFragment.java

private void setAdapter(Cursor imagecursor) {

    if (imagecursor.getCount() > 0) {

        mGalleryModelList = new ArrayList<MediaModel>();

        for (int i = 0; i < imagecursor.getCount(); i++) {
            imagecursor.moveToPosition(i);
            int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
            //int thumbnailColumnIndex    = imagecursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA);
            int idColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
            //int idColumnIndex          = imagecursor.getColumnIndex(MediaStore.Images.Thumbnails.IMAGE_ID);
            int bucketColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.BUCKET_ID);
            int orientColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.ImageColumns.ORIENTATION);

            String imgUrl = imagecursor.getString(dataColumnIndex).toString();
            //            boolean selected = false;
            //            if (mSelectedModels != null && mSelectedModels.size() > 0) {
            //               for(String currImgUrl: mSelectedItems) {
            //                  if (currImgUrl.equalsIgnoreCase(imgUrl)) {
            //                     selected = true;
            //                     break;
            //                  }
            //               }
            //            }

            String id = imagecursor.getString(idColumnIndex);
            String thumbId = "";//imagecursor.getString(idColumnIndex);
            String bucketId = imagecursor.getString(bucketColumnIndex);
            String thumbUrl = "";//imagecursor.getString(thumbnailColumnIndex).toString();
            int orientation = imagecursor.getInt(orientColumnIndex);

            MediaModel galleryModel = new MediaModel(bucketId, id, imgUrl, thumbId, thumbUrl, false,
                    MediaType.IMAGE);/* w w  w .  j  a v a  2  s .  co  m*/
            if (mSelectedModels != null && mSelectedModels.size() > 0) {
                galleryModel.status = mSelectedModels.contains(galleryModel);
            }
            galleryModel.orientation = orientation;

            //processThumbnailImage(id, galleryModel, getActivity());

            mGalleryModelList.add(galleryModel);
        }

        mImageAdapter = new GridViewAdapter(getActivity(), 0, mGalleryModelList, false);
        mImageGridView.setAdapter(mImageAdapter);
    } else {
        Toast.makeText(getActivity(), getActivity().getString(R.string.no_media_file_available),
                Toast.LENGTH_SHORT).show();
    }

    mImageGridView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            GridViewAdapter adapter = (GridViewAdapter) parent.getAdapter();
            MediaModel galleryModel = (MediaModel) adapter.getItem(position);
            File file = new File(galleryModel.url);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(file), "image/*");
            startActivity(intent);
            return true;
        }
    });

    mImageGridView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // update the mStatus of each category in the adapter
            GridViewAdapter adapter = (GridViewAdapter) parent.getAdapter();
            MediaModel galleryModel = (MediaModel) adapter.getItem(position);

            if (!galleryModel.status) {
                long size = MediaChooserConstants.ChekcMediaFileSize(new File(galleryModel.url.toString()),
                        false);
                if (size != 0) {
                    Toast.makeText(getActivity(),
                            getActivity().getResources().getString(R.string.file_size_exeeded) + "  "
                                    + MediaChooserConstants.SELECTED_IMAGE_SIZE_IN_MB + " "
                                    + getActivity().getResources().getString(R.string.mb),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                if (MediaChooserConstants.MAX_MEDIA_LIMIT == 1) {
                    //remove all first
                    if (mSelectedModels.size() >= 1) {

                        MediaModel selModel = (MediaModel) mSelectedModels.get(0);
                        selModel.status = false;

                        mSelectedModels.clear();
                        MediaChooserConstants.SELECTED_MEDIA_COUNT--;
                    }
                }

                if ((MediaChooserConstants.MAX_MEDIA_LIMIT == MediaChooserConstants.SELECTED_MEDIA_COUNT)) {
                    if (MediaChooserConstants.SELECTED_MEDIA_COUNT < 2) {
                        Toast.makeText(getActivity(),
                                getActivity().getResources().getString(R.string.max_limit_file) + "  "
                                        + MediaChooserConstants.SELECTED_MEDIA_COUNT + " "
                                        + getActivity().getResources().getString(R.string.file),
                                Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        Toast.makeText(getActivity(),
                                getActivity().getResources().getString(R.string.max_limit_file) + "  "
                                        + MediaChooserConstants.SELECTED_MEDIA_COUNT + " "
                                        + getActivity().getResources().getString(R.string.files),
                                Toast.LENGTH_SHORT).show();
                        return;
                    }

                }
            }

            // inverse the status
            galleryModel.status = !galleryModel.status;

            adapter.notifyDataSetChanged();

            if (galleryModel.status) {
                //mSelectedItems.add(galleryModel.url.toString());
                mSelectedModels.add(galleryModel);
                MediaChooserConstants.SELECTED_MEDIA_COUNT++;

            } else {
                //mSelectedItems.remove(galleryModel.url.toString().trim());
                mSelectedModels.remove(galleryModel);
                MediaChooserConstants.SELECTED_MEDIA_COUNT--;
            }

            if (mCallback != null) {

                mCallback.onImageSelectedCount(mSelectedModels.size());

                if (galleryModel.status) {
                    mCallback.onImageSelected(galleryModel);
                } else {
                    mCallback.onImageUnselected(galleryModel);
                }

                Intent intent = new Intent();
                //intent.putStringArrayListExtra("list", mSelectedItems);
                intent.putParcelableArrayListExtra("selectedImages", mSelectedModels);
                getActivity().setResult(Activity.RESULT_OK, intent);
            }

        }
    });
}

From source file:de.fahrgemeinschaft.RideDetailsFragment.java

@Override
public void onClick(View v) {
    Cursor c = getCursor();
    if (c.getCount() > 0) {
        if (getCursor().getCount() <= selected)
            selected = c.getCount() - 1;
        c.moveToPosition(selected);
        Util.openContactOptionsChooserDialog(getActivity(), getCursor());
    }//  w w w  . j a  v a 2  s  .c  om
}

From source file:org.dvbviewer.controller.ui.fragments.ChannelEpg.java

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    if (getUserVisibleHint()) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getActivity().getMenuInflater().inflate(R.menu.context_menu_epg, menu);
        MenuItem switchItem = menu.findItem(R.id.menuSwitch)
                .setVisible(URLUtil.isValidUrl(ServerConsts.DVBVIEWER_URL));
        switchItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {

            @Override/*from w w  w  .j  ava 2  s .  c o  m*/
            public boolean onMenuItemClick(MenuItem item) {
                if (getUserVisibleHint()) {
                    String switchRequest = ServerConsts.URL_SWITCH_COMMAND + mCHannel.getPosition();
                    DVBViewerCommand command = new DVBViewerCommand(switchRequest);
                    Thread exexuterTHread = new Thread(command);
                    exexuterTHread.start();
                    return true;
                }
                return false;
            }
        });
        /**
         * Damn Hack for Tablets, onContextItemSelected is not called,
         * But the Dialog appears...
         */
        if (UIUtils.isTablet(getActivity())) {
            menu.findItem(R.id.menuTimer).setOnMenuItemClickListener(new OnMenuItemClickListener() {

                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    if (getUserVisibleHint()) {
                        Cursor c = mAdapter.getCursor();
                        c.moveToPosition(selectedPosition);
                        Timer timer = cursorToTimer(c);
                        TimerDetails timerdetails = TimerDetails.newInstance();
                        Bundle args = new Bundle();
                        args.putString(TimerDetails.EXTRA_TITLE, timer.getTitle());
                        args.putString(TimerDetails.EXTRA_CHANNEL_NAME, timer.getChannelName());
                        args.putLong(TimerDetails.EXTRA_CHANNEL_ID, timer.getChannelId());
                        args.putLong(TimerDetails.EXTRA_START, timer.getStart().getTime());
                        args.putLong(TimerDetails.EXTRA_END, timer.getEnd().getTime());
                        timerdetails.setArguments(args);
                        timerdetails.show(getSherlockActivity().getSupportFragmentManager(),
                                TimerDetails.class.getName());
                        return true;
                    }
                    return false;
                }
            });
        }
    }
}

From source file:org.dvbviewer.controller.ui.fragments.ChannelEpg.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    if (item.getMenuInfo() != null) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        selectedPosition = info.position;
    }//  ww w  .  j ava 2s . c  om
    Cursor c;
    c = mAdapter.getCursor();
    c.moveToPosition(selectedPosition);
    Timer timer;
    if (getUserVisibleHint()) {
        switch (item.getItemId()) {
        case R.id.menuRecord:
            timer = cursorToTimer(c);
            String url = timer.getId() <= 0l ? ServerConsts.URL_TIMER_CREATE : ServerConsts.URL_TIMER_EDIT;
            String title = timer.getTitle();
            String days = String.valueOf(DateUtils.getDaysSinceDelphiNull(timer.getStart()));
            String start = String.valueOf(DateUtils.getMinutesOfDay(timer.getStart()));
            String stop = String.valueOf(DateUtils.getMinutesOfDay(timer.getEnd()));
            String endAction = String.valueOf(timer.getTimerAction());
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("ch", String.valueOf(timer.getChannelId())));
            params.add(new BasicNameValuePair("dor", days));
            params.add(new BasicNameValuePair("encoding", "255"));
            params.add(new BasicNameValuePair("enable", "1"));
            params.add(new BasicNameValuePair("start", start));
            params.add(new BasicNameValuePair("stop", stop));
            params.add(new BasicNameValuePair("title", title));
            params.add(new BasicNameValuePair("endact", endAction));
            if (timer.getId() > 0) {
                params.add(new BasicNameValuePair("id", String.valueOf(timer.getId())));
            }

            String query = URLEncodedUtils.format(params, "utf-8");
            String request = url + query;
            RecordingServiceGet rsGet = new RecordingServiceGet(request);
            Thread executionThread = new Thread(rsGet);
            executionThread.start();
            return true;
        case R.id.menuTimer:
            timer = cursorToTimer(c);
            if (!UIUtils.isTablet(getActivity())) {
                Intent timerIntent = new Intent(getActivity(), TimerDetailsActivity.class);
                timerIntent.putExtra(TimerDetails.EXTRA_TITLE, timer.getTitle());
                timerIntent.putExtra(TimerDetails.EXTRA_CHANNEL_NAME, timer.getChannelName());
                timerIntent.putExtra(TimerDetails.EXTRA_CHANNEL_ID, timer.getChannelId());
                timerIntent.putExtra(TimerDetails.EXTRA_START, timer.getStart().getTime());
                timerIntent.putExtra(TimerDetails.EXTRA_END, timer.getEnd().getTime());
                startActivity(timerIntent);
            }
            return true;
        case R.id.menuDetails:
            Intent details = new Intent(getActivity(), IEpgDetailsActivity.class);
            c = mAdapter.getCursor();
            c.moveToPosition(selectedPosition);
            IEPG entry = cursorToEpgEntry(c);
            details.putExtra(IEPG.class.getSimpleName(), entry);
            startActivity(details);
            return true;
        default:
            break;
        }
    }
    return false;
}

From source file:com.jaspersoft.android.jaspermobile.db.migrate.SavedItemsMigrationV3Test.java

@Test
public void savedItemsShouldBeMigratedToDatabase() throws IOException {
    File savedItemsDir = createSavedReportsDir();
    populateSavedReportsDir(savedItemsDir);

    migration.migrate(database);/* w w  w  .  j a  v a2  s . c o  m*/

    Cursor cursor = database.query("saved_items", new String[] { "_id", "file_path", "name", "file_format",
            "wstype", "account_name", "creation_time" }, null, null, null, null, null);
    assertThat(cursor, notNullValue());
    assertThat(cursor.getCount(), is(2));

    File sharedDir = new File(savedItemsDir, SHARED_DIR);
    File[] savedReportsDirs = sharedDir.listFiles();

    for (int i = 0; i < savedReportsDirs.length; i++) {
        File reportDir = savedReportsDirs[i];
        File report = new File(reportDir, reportDir.getName());
        assertThat(cursor.moveToPosition(i), is(true));

        String fileName = FileUtils.getBaseName(report.getName());
        String fileFormat = FileUtils.getExtension(report.getName()).toUpperCase(Locale.getDefault());
        long creationTime = reportDir.lastModified();

        assertThat(reportDir.listFiles().length, is(2));
        assertThat(cursor.getString(cursor.getColumnIndex("file_path")), is(report.getPath()));
        assertThat(cursor.getString(cursor.getColumnIndex("name")), is(fileName));
        assertThat(cursor.getString(cursor.getColumnIndex("file_format")), is(fileFormat));
        assertThat(cursor.getString(cursor.getColumnIndex("wstype")), is("unknown"));
        assertThat(cursor.getString(cursor.getColumnIndex("account_name")), is("com.jaspersoft.account.none"));
        assertThat(cursor.getString(cursor.getColumnIndex("creation_time")), is(String.valueOf(creationTime)));
    }
}

From source file:com.money.manager.ex.investment.watchlist.WatchlistItemsFragment.java

/**
 * Context menu click handler. Update individual price.
 * @param item selected context menu item.
 * @return indicator whether the action is handled or not.
 *///from   w w  w .  j a  v a  2  s  .co  m
@Override
public boolean onContextItemSelected(android.view.MenuItem item) {
    ContextMenu.ContextMenuInfo menuInfo = item.getMenuInfo();
    if (!(menuInfo instanceof AdapterView.AdapterContextMenuInfo))
        return false;

    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    //        ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) ;

    Cursor cursor = ((StocksCursorAdapter) getListAdapter()).getCursor();
    //        long packedPosition = hasHeaderRow() ? info.packedPosition - 1 : info.packedPosition;
    int cursorPosition = hasHeaderRow() ? info.position - 1 : info.position;
    cursor.moveToPosition(cursorPosition);

    Stock stock = Stock.from(cursor);
    String symbol = stock.getSymbol();

    boolean result = false;
    ContextMenuIds menuId = ContextMenuIds.get(item.getItemId());

    switch (menuId) {
    case DownloadPrice:
        // Update price
        EventBus.getDefault().post(new PriceUpdateRequestEvent(symbol));
        result = true;
        break;

    case EditPrice:
        // Edit price
        int accountId = stock.getHeldAt();
        Money currentPrice = stock.getCurrentPrice();

        //todo Intent intent = IntentFactory.getPriceEditIntent(getActivity());

        EditPriceDialog dialog = new EditPriceDialog();
        Bundle args = new Bundle();
        args.putInt(EditPriceDialog.ARG_ACCOUNT, accountId);
        args.putString(EditPriceDialog.ARG_SYMBOL, symbol);
        args.putString(EditPriceDialog.ARG_PRICE, currentPrice.toString());

        String dateString = new MmxDate().toIsoString();
        args.putString(EditPriceDialog.ARG_DATE, dateString);

        dialog.setArguments(args);
        dialog.show(getChildFragmentManager(), "input-amount");
        break;

    case DELETE:
        showDeleteConfirmationDialog(stock.getId());
        break;
    }

    return result;
}