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.money.manager.ex.fragment.AllDataFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // set fragment
    setEmptyText(getString(R.string.no_data));
    setListShown(false);/*  w  w  w.  j  ava2 s .com*/
    // option menu
    setHasOptionsMenu(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
    // create adapter
    AllDataAdapter adapter = new AllDataAdapter(getActivity(), null, TypeCursor.ALLDATA);
    adapter.setAccountId(mAccountId);
    adapter.setShowAccountName(isShownHeader());
    adapter.setShowBalanceAmount(isShownBalance());
    if (isShownBalance()) {
        adapter.setDatabase(new MoneyManagerOpenHelper(getActivity()).getReadableDatabase());
    }
    // set choice mode in listview
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mMultiChoiceModeListener = new AllDataMultiChoiceModeListener();
        getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        getListView().setMultiChoiceModeListener(mMultiChoiceModeListener);
    }
    // click item
    getListView().setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (getListAdapter() != null && getListAdapter() instanceof AllDataAdapter) {
                Cursor cursor = ((AllDataAdapter) getListAdapter()).getCursor();
                if (cursor.moveToPosition(position)) {
                    startCheckingAccountActivity(cursor.getInt(cursor.getColumnIndex(QueryAllData.ID)));
                }
            }
        }
    });
    // set adapter
    setListAdapter(adapter);
    // register context menu
    registerForContextMenu(getListView());
    // set divider
    /*Core core = new Core(getSherlockActivity());
    if (core.getThemeApplication() == R.style.Theme_Money_Manager_Light_DarkActionBar)
     getListView().setDivider(new ColorDrawable(new Core(getSherlockActivity()).resolveIdAttribute(R.attr.theme_background_color)));*/
    //getListView().setSelector(new ColorDrawable(getResources().getColor(R.color.money_background)));
    // set animation
    setListShown(false);
    // start loader
    if (isAutoStarLoader()) {
        startLoaderData();
    }
}

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

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Cursor c = mAdapter.getCursor();
    c.moveToPosition(position);
    IEPG entry = cursorToEpgEntry(c);/*from   w  w w . j  a v a 2s. co m*/

    Intent i = new Intent(getActivity(), IEpgDetailsActivity.class);
    i.putExtra(IEPG.class.getSimpleName(), entry);
    startActivity(i);
}

From source file:com.ksharkapps.musicnow.ui.activities.SearchActivity.java

/**
 * {@inheritDoc}// w ww  .j  a v  a  2 s.c  o m
 */
@Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
    Cursor cursor = mAdapter.getCursor();
    cursor.moveToPosition(position);
    if (cursor.isBeforeFirst() || cursor.isAfterLast()) {
        return;
    }
    // Get the MIME type
    final String mimeType = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.MIME_TYPE));

    // If it's an artist, open the artist profile
    if ("artist".equals(mimeType)) {
        NavUtils.openArtistProfile(this,
                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST)));
    } else if ("album".equals(mimeType)) {
        // If it's an album, open the album profile
        NavUtils.openAlbumProfile(this,
                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM)),
                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ARTIST)),
                cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums._ID)));
    } else if (position >= 0 && id >= 0) {
        // If it's a song, play it and leave
        final long[] list = new long[] { id };
        MusicUtils.playAll(this, list, 0, false);
    }

    // Close it up
    cursor.close();
    cursor = null;
    // All done
    finish();
}

From source file:io.github.tjg1.nori.SearchActivity.java

/**
 * Set up the action bar SearchView and its event handlers.
 *
 * @param menu Menu after being inflated in {@link #onCreateOptionsMenu(android.view.Menu)}.
 *///from   w  ww. jav  a  2  s.c o m
private void setUpSearchView(Menu menu) {
    // Extract SearchView from the MenuItem object.
    searchMenuItem = menu.findItem(R.id.action_search);
    searchMenuItem.setVisible(searchClientSettings != null);
    searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);

    // Set Searchable XML configuration.
    SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    // Set SearchView attributes.
    searchView.setFocusable(false);
    searchView.setQueryRefinementEnabled(true);

    // Set submit action and allow empty queries.
    SearchView.SearchAutoComplete searchTextView = (SearchView.SearchAutoComplete) searchView
            .findViewById(R.id.search_src_text);
    searchTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
            CharSequence query = textView.getText();
            if (query != null && searchClientSettings != null) {
                // Prepare a intent to send to a new instance of this activity.
                Intent intent = new Intent(SearchActivity.this, SearchActivity.class);
                intent.setAction(Intent.ACTION_SEARCH);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(BUNDLE_ID_SEARCH_CLIENT_SETTINGS, searchClientSettings);
                intent.putExtra(BUNDLE_ID_SEARCH_QUERY, query.toString());

                // Collapse the ActionView. This makes navigating through previous results using the back key less painful.
                MenuItemCompat.collapseActionView(searchMenuItem);

                // Start a new activity with the created Intent.
                startActivity(intent);
            }

            // Returns true to override the default behaviour and stop another search Intent from being sent.
            return true;
        }
    });

    searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
        @Override
        public boolean onSuggestionSelect(int position) {
            return onSuggestionClick(position);
        }

        @Override
        public boolean onSuggestionClick(int position) {
            if (searchClientSettings != null) {
                // Get the SearchView's suggestion adapter.
                CursorAdapter adapter = searchView.getSuggestionsAdapter();
                // Get the suggestion at given position.
                Cursor c = adapter.getCursor();
                c.moveToPosition(position);

                // Create and send a search intent.
                Intent intent = new Intent(SearchActivity.this, SearchActivity.class);
                intent.setAction(Intent.ACTION_SEARCH);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(BUNDLE_ID_SEARCH_CLIENT_SETTINGS, searchClientSettings);
                intent.putExtra(BUNDLE_ID_SEARCH_QUERY,
                        c.getString(c.getColumnIndex(SearchSuggestionDatabase.COLUMN_NAME)));
                startActivity(intent);

                // Release native resources.
                c.close();
            }

            // Return true to override default behaviour and prevent another intent from being sent.
            return true;
        }
    });

    if (savedInstanceState != null) {
        // Restore state from saved instance state bundle (after screen rotation, app restored from background, etc.)
        if (savedInstanceState.containsKey(BUNDLE_ID_SEARCH_QUERY)) {
            // Restore search query from saved instance state.
            searchView.setQuery(savedInstanceState.getCharSequence(BUNDLE_ID_SEARCH_QUERY), false);
        }
        // Restore iconified/expanded search view state from saved instance state.
        if (savedInstanceState.getBoolean(BUNDLE_ID_SEARCH_VIEW_IS_EXPANDED, false)) {
            MenuItemCompat.expandActionView(searchMenuItem);
            // Restore focus state.
            if (!savedInstanceState.getBoolean(BUNDLE_ID_SEARCH_VIEW_IS_FOCUSED, false)) {
                searchView.clearFocus();
            }
        }
    } else if (getIntent() != null && getIntent().getAction().equals(Intent.ACTION_SEARCH)) {
        // Set SearchView query string to match the one sent in the SearchIntent.
        searchView.setQuery(getIntent().getStringExtra(BUNDLE_ID_SEARCH_QUERY), false);
    }
}

From source file:org.mariotaku.twidere.activity.support.DraftsActivity.java

@Override
public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) {
    switch (item.getItemId()) {
    case MENU_DELETE: {
        // TODO confim dialog and image removal
        final Where where = Where.in(new Column(Drafts._ID), new RawItemArray(mListView.getCheckedItemIds()));
        mResolver.delete(Drafts.CONTENT_URI, where.getSQL(), null);
        break;/*from   ww w . j a v  a 2 s  .co m*/
    }
    case MENU_SEND: {
        final Cursor c = mAdapter.getCursor();
        if (c == null || c.isClosed())
            return false;
        final SparseBooleanArray checked = mListView.getCheckedItemPositions();
        final List<DraftItem> list = new ArrayList<DraftItem>();
        final DraftItem.CursorIndices indices = new DraftItem.CursorIndices(c);
        for (int i = 0, j = checked.size(); i < j; i++) {
            if (checked.valueAt(i) && c.moveToPosition(checked.keyAt(i))) {
                list.add(new DraftItem(c, indices));
            }
        }
        if (sendDrafts(list)) {
            final Where where = Where.in(new Column(Drafts._ID),
                    new RawItemArray(mListView.getCheckedItemIds()));
            mResolver.delete(Drafts.CONTENT_URI, where.getSQL(), null);
        }
        break;
    }
    default: {
        return false;
    }
    }
    mode.finish();
    return true;
}

From source file:com.money.manager.ex.currency.list.CurrencyListFragment.java

@Override
protected void setResult() {
    Intent result;/* w  ww  . ja  va2  s.  co m*/
    if (Intent.ACTION_PICK.equals(mAction)) {
        // create intent
        Cursor cursor = ((CurrencyListAdapter) getListAdapter()).getCursor();

        for (int i = 0; i < getListView().getCount(); i++) {
            if (getListView().isItemChecked(i)) {
                cursor.moveToPosition(i);

                result = new Intent();
                result.putExtra(CurrencyListActivity.INTENT_RESULT_CURRENCYID,
                        cursor.getInt(cursor.getColumnIndex(Currency.CURRENCYID)));
                result.putExtra(CurrencyListActivity.INTENT_RESULT_CURRENCYNAME,
                        cursor.getString(cursor.getColumnIndex(Currency.CURRENCYNAME)));

                getActivity().setResult(Activity.RESULT_OK, result);

                return;
            }
        }
    }
    getActivity().setResult(CurrencyListActivity.RESULT_CANCELED);
}

From source file:info.guardianproject.otr.app.im.app.AccountListActivity.java

protected void openAccountAtPosition(int position) {
    Cursor cursor = mAdapter.getCursor();
    cursor.moveToPosition(position);

    if (cursor.isNull(ACTIVE_ACCOUNT_ID_COLUMN)) {
        showExistingAccountListDialog();

    } else {//from w  ww  .j a  v  a  2 s.  c o m

        int state = cursor.getInt(ACCOUNT_CONNECTION_STATUS);
        long accountId = cursor.getLong(ACTIVE_ACCOUNT_ID_COLUMN);

        if (state == Imps.ConnectionStatus.OFFLINE) {

            Intent intent = getEditAccountIntent();
            startActivity(intent);

        } else {
            gotoAccount(accountId);
        }

    }

}

From source file:org.smssecure.smssecure.contacts.ContactSelectionListAdapter.java

@Override
public View getHeaderView(int i, View convertView, ViewGroup viewGroup) {
    final Cursor c = getCursor();
    final HeaderViewHolder holder;
    if (convertView == null) {
        holder = new HeaderViewHolder();
        convertView = li.inflate(R.layout.push_contact_selection_list_header, viewGroup, false);
        holder.text = (TextView) convertView.findViewById(R.id.text);
        convertView.setTag(holder);/*from  w w  w. jav  a 2 s. c o  m*/
    } else {
        holder = (HeaderViewHolder) convertView.getTag();
    }
    c.moveToPosition(i);

    final int type = c.getInt(c.getColumnIndexOrThrow(ContactsDatabase.TYPE_COLUMN));
    final int headerTextRes;
    // TODO: Remove push-related code
    switch (type) {
    case 1:
        headerTextRes = R.string.contact_selection_list__header;
        break;
    default:
        headerTextRes = R.string.contact_selection_list__header;
        break;
    }
    holder.text.setText(headerTextRes);
    return convertView;
}

From source file:com.securecomcode.text.contacts.ContactSelectionListAdapter.java

@Override
public View getHeaderView(int i, View convertView, ViewGroup viewGroup) {
    final Cursor c = getCursor();
    final HeaderViewHolder holder;
    if (convertView == null) {
        holder = new HeaderViewHolder();
        convertView = li.inflate(R.layout.push_contact_selection_list_header, viewGroup, false);
        holder.text = (TextView) convertView.findViewById(R.id.text);
        convertView.setTag(holder);//ww  w . j  a  v a  2 s  . c o m
    } else {
        holder = (HeaderViewHolder) convertView.getTag();
    }
    c.moveToPosition(i);

    final int type = c.getInt(c.getColumnIndexOrThrow(ContactsDatabase.TYPE_COLUMN));
    final int headerTextRes;
    switch (type) {
    case 1:
        headerTextRes = R.string.contact_selection_list__header_textsecure_users;
        break;
    default:
        headerTextRes = R.string.contact_selection_list__header_other;
        break;
    }
    holder.text.setText(headerTextRes);
    return convertView;
}

From source file:org.opendatakit.common.android.provider.impl.InstanceProviderImpl.java

/**
 * This method removes the entry from the content provider, and also removes
 * any associated files. files: form.xml, [formmd5].formdef, formname
 * {directory}/*  www. j a  v  a2 s  .  c om*/
 */
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 2 || segments.size() > 3) {
        throw new SQLException("Unknown URI (too many segments!) " + uri);
    }

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    String tableId = segments.get(1);
    // _ID in UPLOADS_TABLE_NAME
    String instanceId = (segments.size() == 3 ? segments.get(2) : null);

    SQLiteDatabase db = null;
    List<IdStruct> idStructs = new ArrayList<IdStruct>();
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();

        boolean success = false;
        try {
            success = ODKDatabaseUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException("Unknown URI (exception testing for tableId) " + uri);
        }
        if (!success) {
            throw new SQLException("Unknown URI (missing data table for tableId) " + uri);
        }

        String dbTableName = "\"" + tableId + "\"";

        if (segments.size() == 2) {
            where = "(" + where + ") AND (" + InstanceColumns.DATA_INSTANCE_ID + "=? )";
            if (whereArgs != null) {
                String[] args = new String[whereArgs.length + 1];
                for (int i = 0; i < whereArgs.length; ++i) {
                    args[i] = whereArgs[i];
                }
                args[whereArgs.length] = instanceId;
                whereArgs = args;
            } else {
                whereArgs = new String[] { instanceId };
            }
        }

        Cursor del = null;
        try {
            del = this.query(uri, null, where, whereArgs, null);
            del.moveToPosition(-1);
            while (del.moveToNext()) {
                String iId = ODKDatabaseUtils.get().getIndexAsString(del,
                        del.getColumnIndex(InstanceColumns._ID));
                String iIdDataTable = ODKDatabaseUtils.get().getIndexAsString(del,
                        del.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID));
                idStructs.add(new IdStruct(iId, iIdDataTable));
                String path = ODKFileUtils.getInstanceFolder(appName, tableId, iIdDataTable);
                File f = new File(path);
                if (f.exists()) {
                    if (f.isDirectory()) {
                        FileUtils.deleteDirectory(f);
                    } else {
                        f.delete();
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("Unable to delete instance directory: " + e.toString());
        } finally {
            if (del != null) {
                del.close();
            }
        }

        for (IdStruct idStruct : idStructs) {
            db.delete(DatabaseConstants.UPLOADS_TABLE_NAME, InstanceColumns.DATA_INSTANCE_ID + "=?",
                    new String[] { idStruct.idUploadsTable });
            db.delete(dbTableName, DATA_TABLE_ID_COLUMN + "=?", new String[] { idStruct.idDataTable });
        }
        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return idStructs.size();
}