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.example.android.ennis.barrett.popularmovies.asynchronous.TMDbSyncUtil.java

/**
 * Parses and stores the JSON data in the TMDbContentProvider
 * @param dataJSON The JSON data from server
 * @param type Flag for the try of movie to fetch.  Should match flag used in fetchMovies
 * @throws JSONException//from  ww w .j a v a  2  s.co m
 */
private static int[] storeJsonMovies(String dataJSON, int type, Context context) throws JSONException {
    //TODO use ContentProviderClient instead of ContentResolver
    try {
        JSONObject moviesJSON = new JSONObject(dataJSON);
        JSONArray results = moviesJSON.getJSONArray("results");
        final int resultLength = results.length();
        ContentValues[] contentValues = new ContentValues[resultLength];
        int[] ids = new int[resultLength];
        int isPopular;
        int isTopRated;
        int isFavorite;

        switch (type) {
        case MOVIES_POPULAR:
            isPopular = 1;
            isTopRated = 0;
            break;
        case MOVIES_TOP_RATED:
            isPopular = 0;
            isTopRated = 1;
            break;
        default:
            isPopular = 0;
            isTopRated = 0;
        }
        Cursor cursor = getFavoriteIds(context);
        ContentResolver contentResolver = context.getContentResolver();

        for (int i = 0; i < resultLength; i++) {
            JSONObject movie = results.getJSONObject(i);
            contentValues[i] = new ContentValues();
            contentValues[i].put(TMDbContract.Movies.ORIGINAL_TITLE,
                    movie.getString(TMDbContract.Movies.ORIGINAL_TITLE));

            contentValues[i].put(TMDbContract.Movies.OVERVIEW, movie.getString(TMDbContract.Movies.OVERVIEW));
            contentValues[i].put(TMDbContract.Movies.POSTER, movie.getString(TMDbContract.Movies.POSTER));
            contentValues[i].put(TMDbContract.Movies.RELEASE_DATE,
                    movie.getString(TMDbContract.Movies.RELEASE_DATE));
            contentValues[i].put(TMDbContract.Movies.POPULARITY,
                    movie.getDouble(TMDbContract.Movies.POPULARITY));
            contentValues[i].put(TMDbContract.Movies.VOTE_AVERAGE,
                    movie.getDouble(TMDbContract.Movies.VOTE_AVERAGE));

            int moveId = movie.getInt(TMDbContract.Movies.MOVIE_ID);
            contentValues[i].put(TMDbContract.Movies.MOVIE_ID, moveId);
            cursor.moveToPosition(-1);
            while (cursor.moveToNext()) {
                int favoriteId = cursor.getInt(cursor.getColumnIndex(TMDbContract.Movies.MOVIE_ID));
                if (favoriteId == moveId) {
                    deleteFavorite(context, moveId);
                    isFavorite = 1;
                    contentValues[i].put(TMDbContract.Movies.IS_FAVORITE, isFavorite);
                    break;
                }
            }

            //TODO read up on how to have the col initialized to 0 by defualt
            contentValues[i].put(TMDbContract.Movies.IS_POPULAR, isPopular);
            contentValues[i].put(TMDbContract.Movies.IS_TOP_RATED, isTopRated);

            ids[i] = movie.getInt(TMDbContract.Movies.MOVIE_ID);
        }

        int numInserted = contentResolver.bulkInsert(TMDbContract.Movies.URI, contentValues);

        if (numInserted != resultLength) {
            Log.e(TAG, "Not all of the result were inserted.\n Amount inserted: " + numInserted
                    + "\nAmount from server: " + resultLength);
        }

        return ids;
    } catch (JSONException e) {
        Log.d(TAG, e.getMessage(), e);
        e.printStackTrace();
        return null;
    }
}

From source file:org.mariotaku.twidere.fragment.support.DraftsFragment.java

@Override
public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) {
    switch (item.getItemId()) {
    case MENU_DELETE: {
        final DeleteDraftsConfirmDialogFragment f = new DeleteDraftsConfirmDialogFragment();
        final Bundle args = new Bundle();
        args.putLongArray(EXTRA_IDS, mListView.getCheckedItemIds());
        f.setArguments(args);/*from  w ww  .j  a  va 2s. c  o m*/
        f.show(getChildFragmentManager(), "delete_drafts_confirm");
        break;
    }
    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<>();
        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 Expression where = Expression.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.polyvi.xface.extension.messaging.XMessagingExt.java

/**
 * ?//from   www  .  ja v a  2  s .c  o m
 *
 * @param comparisonMsg
 *            ??
 * @param folderType
 *            
 * @param startIndex
 *            
 * @param endIndex
 *            ?
 * @return ?
 */
private JSONArray findMessages(JSONObject comparisonMsg, String folderType, int startIndex, int endIndex)
        throws JSONException {
    // TODO:???Email?
    if (null == folderType) {// folderTypenull?
        folderType = FOLDERTYPE_DRAFT;
    }

    ArrayList<String> projections = new ArrayList<String>();
    projections.add("_id");
    projections.add("subject");
    projections.add("address");
    projections.add("body");
    ArrayList<String> projectionsValue = new ArrayList<String>();
    projectionsValue.add(comparisonMsg.optString("messageId"));
    projectionsValue.add(comparisonMsg.optString("subject"));
    projectionsValue.add(comparisonMsg.optString("destinationAddresses"));
    projectionsValue.add(comparisonMsg.optString("body"));

    StringBuilder selection = XUtils.constructSelectionStatement(projections, projectionsValue);

    int isRead = comparisonMsg.getInt("isRead");
    if (-1 != isRead) {
        if (null == selection) {
            selection = new StringBuilder();
        } else {
            selection.append(" AND ");
        }
        selection.append("read");
        selection.append("=");
        selection.append(isRead);
    }
    String selectionStr = null;
    if (null != selection) {
        selectionStr = selection.toString();
    }

    folderType = folderType.toLowerCase();
    Uri findUri = Uri.withAppendedPath(mSMSContentUri, folderType);
    JSONArray messages = new JSONArray();
    try {
        ContentResolver resolver = mContext.getContentResolver();
        Cursor cursor = resolver.query(findUri, null, selectionStr, null, null);
        if (null == cursor) {
            return messages;
        }
        int count = endIndex - startIndex + 1;
        if (cursor.moveToPosition(startIndex)) {
            do {
                JSONObject message = getMessageFromCursor(cursor);
                messages.put(message);
                count--;
            } while (cursor.moveToNext() && count > 0);
        }
        cursor.close();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
    }
    return messages;
}

From source file:com.polyvi.xface.extension.camera.XCameraExt.java

private void photoSucess(Intent intent) {
    //URI????URI?URI??
    //???try-catch???
    Uri uri = intent.getData();/*from  w  ww.j  a va2s.  c  o  m*/
    if (null == uri) {
        uri = mImageUri;
    }
    ContentResolver resolver = getContext().getContentResolver();
    XPathResolver pathResolver = new XPathResolver(null == uri ? null : uri.toString(), "", getContext());
    Bitmap bitmap = null;
    try {
        if (!mAllowEdit) {
            String path = pathResolver.resolve();
            if (!XStringUtils.isEmptyString(path)) {
                bitmap = XUtils.decodeBitmap(path);
            }
        } else {
            //??????Android???
            bitmap = intent.getExtras().getParcelable("data");

            //?????URI
            if (bitmap == null) {
                bitmap = getCroppedBitmap(intent);
            }
        }
    } catch (OutOfMemoryError e) {
        mCallbackCtx.error("OutOfMemoryError when decode image.");
        return;
    }
    if (mDestType == DATA_URL) {
        int rotate = 0;
        String[] cols = { MediaStore.Images.Media.ORIENTATION };
        Cursor cursor = resolver.query(uri, cols, null, null, null);
        if (null != cursor) {
            cursor.moveToPosition(0);
            rotate = cursor.getInt(0);
            cursor.close();
        }
        if (0 != rotate) {
            Matrix matrix = new Matrix();
            matrix.setRotate(rotate);
            bitmap = bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        }
        bitmap = scaleBitmap(bitmap);
        processPicture(bitmap);
        bitmap.recycle();
        bitmap = null;
        System.gc();
    } else if (mTargetHeight > 0 && mTargetWidth > 0) {
        try {
            Bitmap scaleBitmap = scaleBitmap(bitmap);

            String fileName = XConfiguration.getInstance().getWorkDirectory() + RESIZED_PIC_NAME;
            OutputStream os = new FileOutputStream(fileName);
            scaleBitmap.compress(Bitmap.CompressFormat.JPEG, mQuality, os);
            os.close();

            bitmap.recycle();
            bitmap = null;
            scaleBitmap.recycle();
            scaleBitmap = null;

            mCallbackCtx.success("file://" + fileName + "?" + System.currentTimeMillis());
            System.gc();
        } catch (Exception e) {
            mCallbackCtx.error("Error retrieving image.");
            return;
        }
    } else {
        mCallbackCtx.success(XConstant.FILE_SCHEME + pathResolver.resolve());
    }
}

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

@Override
public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) {
    switch (item.getItemId()) {
    case R.id.delete: {
        final DeleteDraftsConfirmDialogFragment f = new DeleteDraftsConfirmDialogFragment();
        final Bundle args = new Bundle();
        args.putLongArray(EXTRA_IDS, mListView.getCheckedItemIds());
        f.setArguments(args);// w  ww .j  a  v  a  2 s . c om
        f.show(getChildFragmentManager(), "delete_drafts_confirm");
        break;
    }
    case R.id.send: {
        final Cursor c = mAdapter.getCursor();
        if (c == null || c.isClosed())
            return false;
        final SparseBooleanArray checked = mListView.getCheckedItemPositions();
        final List<Draft> list = new ArrayList<>();
        final DraftCursorIndices indices = new DraftCursorIndices(c);
        for (int i = 0, j = checked.size(); i < j; i++) {
            if (checked.valueAt(i) && c.moveToPosition(checked.keyAt(i))) {
                list.add(indices.newObject(c));
            }
        }
        if (sendDrafts(list)) {
            final Expression where = Expression.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:net.ddns.mlsoftlaberge.trycorder.contacts.ContactsListFragment.java

@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    buttonsound();// ww  w . j  av  a2  s  .  c  om
    // Gets the Cursor object currently bound to the ListView
    final Cursor cursor = mAdapter.getCursor();
    // Moves to the Cursor row corresponding to the ListView item that was clicked
    cursor.moveToPosition(position);
    // Creates a contact lookup Uri from contact ID and lookup_key
    final Uri uri = Contacts.getLookupUri(cursor.getLong(ContactsQuery.ID),
            cursor.getString(ContactsQuery.LOOKUP_KEY));
    // Notifies the parent activity that the user selected a contact. In a two-pane layout, the
    // parent activity loads a ContactAdminFragment that displays the details for the selected
    // contact. In a single-pane layout, the parent activity starts a new activity that
    // displays contact details in its own Fragment.
    mOnContactSelectedListener.onContactSelected(uri);
}

From source file:com.polyvi.xface.extension.telephony.XTelephonyExt.java

/**
 * ??//from   w  w  w. j av  a2s.  c  o m
 *
 * @param[in] comparisonCallRecord ??
 * @param[in] startIndex ?
 * @param[in] endIndex ???
 * @return ???JSON
 */
private JSONArray findCallRecords(JSONObject comparisonCallRecord, int startIndex, int endIndex) {
    JSONArray result = new JSONArray();
    if (null != comparisonCallRecord) {
        try {
            String callRecordId = comparisonCallRecord.getString("callRecordId");
            String callRecordAddress = comparisonCallRecord.getString("callRecordAddress");
            String callRecordName = comparisonCallRecord.getString("callRecordName");
            String callRecordType = comparisonCallRecord.getString("callRecordType");
            long startTime = comparisonCallRecord.getLong("startTime");
            long durationSeconds = comparisonCallRecord.getLong("durationSeconds");

            ArrayList<String> projections = new ArrayList<String>();
            projections.add(CallLog.Calls._ID);
            projections.add(CallLog.Calls.NUMBER);
            projections.add(CallLog.Calls.CACHED_NAME);

            ArrayList<String> projectionsValue = new ArrayList<String>();
            projectionsValue.add(callRecordId);
            projectionsValue.add(callRecordAddress);
            projectionsValue.add(callRecordName);

            StringBuilder selection = XUtils.constructSelectionStatement(projections, projectionsValue);
            String selectionStr = buildSelectionStr(selection, startTime, durationSeconds, callRecordType);
            Cursor cursor = mContentResolver.query(CallLog.Calls.CONTENT_URI, null, selectionStr, null,
                    CallLog.Calls.DEFAULT_SORT_ORDER);
            if (null == cursor) {
                return result;
            }
            int count = endIndex - startIndex + 1;
            if (count > 0) {
                if (cursor.moveToPosition(startIndex)) {
                    do {
                        JSONObject callRecord = getCallRecordFromCursor(cursor);
                        result.put(callRecord);
                        count--;
                    } while (cursor.moveToNext() && count > 0);
                }
            }
            cursor.close();
        } catch (JSONException e) {
            XLog.e(CLASS_NAME, e.toString());
        }
    }
    return result;
}

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

/**
 * Select the current account in the accounts dropdown.
 *///from  w  w  w.j a va 2s. c  om
private void selectCurrentAccount() {
    Spinner spinner = getAccountsSpinner();
    if (spinner == null)
        return;

    // find account
    SimpleCursorAdapter adapter = (SimpleCursorAdapter) spinner.getAdapter();
    if (adapter == null)
        return;

    Cursor cursor = adapter.getCursor();
    int position = Constants.NOT_SET;

    for (int i = 0; i < adapter.getCount(); i++) {
        cursor.moveToPosition(i);
        String accountIdString = cursor.getString(cursor.getColumnIndex(Account.ACCOUNTID));
        int accountId = Integer.parseInt(accountIdString);
        if (accountId == getAccountId()) {
            position = i;
            break;
        }
    }

    spinner.setSelection(position);
}

From source file:com.ute.bihapi.wydarzeniatekstowe.thirdScreenActivities.ContactsListFragment.java

@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    // Gets the Cursor object currently bound to the ListView
    final Cursor cursor = mAdapter.getCursor();

    // Moves to the Cursor row corresponding to the ListView item that was clicked
    cursor.moveToPosition(position);

    // Creates a contact lookup Uri from contact ID and lookup_key
    final Uri uri = Contacts.getLookupUri(cursor.getLong(ContactsQuery.ID),
            cursor.getString(ContactsQuery.LOOKUP_KEY));

    // Notifies the parent activity that the user selected a contact. In a two-pane layout, the
    // parent activity loads a ContactDetailFragment that displays the details for the selected
    // contact. In a single-pane layout, the parent activity starts a new activity that
    // displays contact details in its own Fragment.
    mOnContactSelectedListener.onContactSelected(uri);
    getListView().setItemChecked(position, true);
}

From source file:org.teleportr.Ride.java

private void load(Cursor cursor, Context ctx) {
    cv.put(_ID, cursor.getLong(COLUMNS.ID));
    type(cursor.getInt(COLUMNS.TYPE));/*from w ww .  j a v  a 2  s  .  c  om*/
    from(cursor.getInt(COLUMNS.FROM_ID));
    to(cursor.getInt(COLUMNS.TO_ID));
    dep(cursor.getLong(COLUMNS.DEPARTURE));
    arr(cursor.getLong(COLUMNS.ARRIVAL));
    price(cursor.getInt(COLUMNS.PRICE));
    seats(cursor.getInt(COLUMNS.SEATS));
    cv.put(DIRTY, cursor.getInt(COLUMNS.DIRTY));
    if (cursor.getShort(COLUMNS.MARKED) == 1)
        marked();
    if (cursor.getShort(COLUMNS.ACTIVE) == 1)
        activate();
    String val = cursor.getString(COLUMNS.WHO);
    if (val != null && !val.equals(EMPTY))
        who(val);
    val = cursor.getString(COLUMNS.REF);
    if (val != null && !val.equals(EMPTY))
        ref(val);
    else
        Log.e(RidesProvider.TAG, "REF is NULL! " + this);
    try {
        details = new JSONObject(cursor.getString(COLUMNS.DETAILS));
        mode(Mode.valueOf(cursor.getString(COLUMNS.MODE)));
    } catch (Exception e) {
    }
    Cursor sub_cursor = ctx.getContentResolver().query(RidesProvider.getSubRidesUri(ctx, cursor.getInt(0)),
            null, null, null, null);
    subrides = new ArrayList<ContentValues>();
    for (int i = 0; i < sub_cursor.getCount(); i++) {
        sub_cursor.moveToPosition(i);
        subrides.add(new Ride(sub_cursor, ctx).cv);
    }
    sub_cursor.close();
    this.ctx = ctx;
}