Example usage for android.database Cursor moveToNext

List of usage examples for android.database Cursor moveToNext

Introduction

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

Prototype

boolean moveToNext();

Source Link

Document

Move the cursor to the next row.

Usage

From source file:im.delight.android.commons.Social.java

/**
 * Returns a list of email addresses for the contact with the given lookup ID
 *
 * @param contactLookupId a contact's lookup ID to get the email addresses for
 * @param context a context reference/*w  w w.  jav a 2 s .c  o m*/
 * @return CharSequence[] a list of all email addresses for the given contact or `null`
 */
public static CharSequence[] getContactEmail(final String contactLookupId, final Context context) {
    final Uri uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
    final String[] projection = new String[] { ContactsContract.CommonDataKinds.Email.DATA };
    final String where = ContactsContract.Contacts.LOOKUP_KEY + " = ?";
    final String[] selectionArgs = new String[] { contactLookupId };
    final String sortOrder = null;

    Cursor result = context.getContentResolver().query(uri, projection, where, selectionArgs, sortOrder);

    String email;
    if (result != null) {
        if (result.getCount() > 0) {
            final CharSequence[] res = new CharSequence[result.getCount()];

            int i = 0;
            while (result.moveToNext()) {
                email = result.getString(result.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));

                if (email != null) {
                    res[i] = email;
                    i++;
                }
            }

            result.close();

            return res;
        } else {
            result.close();

            return null;
        }
    } else {
        return null;
    }
}

From source file:com.coinomi.wallet.ExchangeRatesProvider.java

public static List<ExchangeRate> getRates(final Context context, @Nonnull String localSymbol) {
    ImmutableList.Builder<ExchangeRate> builder = ImmutableList.builder();

    if (context != null) {
        final Uri uri = contentUriToCrypto(context.getPackageName(), localSymbol, true);
        final Cursor cursor = context.getContentResolver().query(uri, null, null, new String[] { null }, null);

        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst();/*  w  w w  .  ja v a 2  s.  co  m*/
            do {
                builder.add(getExchangeRate(cursor));
            } while (cursor.moveToNext());
            cursor.close();
        }
    }

    return builder.build();
}

From source file:Main.java

public static void deleteSMS(Context context, String message, String number) {
    try {//from w ww .java  2s . co  m

        Uri uriSms = Uri.parse("content://sms/inbox");
        Cursor c = context.getContentResolver().query(uriSms,
                new String[] { "_id", "thread_id", "address", "person", "date", "body" }, null, null, null);

        if (c != null && c.moveToFirst()) {
            do {
                long id = c.getLong(0);
                long threadId = c.getLong(1);
                String address = c.getString(2);
                String body = c.getString(5);

                if (message.equals(body) && address.equals(number)) {

                    context.getContentResolver().delete(Uri.parse("content://sms/" + id), null, null);
                }
            } while (c.moveToNext());
        }
    } catch (Exception e) {
        // mLogger.logError("Could not delete SMS from inbox: " + e.getMessage());
    }
}

From source file:Main.java

public static ArrayList<String> getAllShownImagesPath(Activity activity) {
    Uri uri;//ww w  .j av a2  s  . co m
    Cursor cursor;
    int column_index_data, column_index_folder_name;
    ArrayList<String> listOfAllImages = new ArrayList<String>();
    String absolutePathOfImage = null;
    uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

    String[] projection = { MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME };

    cursor = activity.getContentResolver().query(uri, projection, null, null, null);

    column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
    while (cursor.moveToNext()) {
        absolutePathOfImage = cursor.getString(column_index_data);

        listOfAllImages.add(absolutePathOfImage);
    }
    return listOfAllImages;
}

From source file:at.bitfire.davdroid.resource.LocalTaskList.java

public static LocalTaskList[] findAll(Account account, ContentProviderClient providerClient)
        throws RemoteException {
    @Cleanup
    Cursor cursor = providerClient.query(taskListsURI(account),
            new String[] { TaskContract.TaskLists._ID, TaskContract.TaskLists._SYNC_ID }, null, null, null);

    LinkedList<LocalTaskList> taskList = new LinkedList<>();
    while (cursor != null && cursor.moveToNext())
        taskList.add(new LocalTaskList(account, providerClient, cursor.getInt(0), cursor.getString(1)));
    return taskList.toArray(new LocalTaskList[taskList.size()]);
}

From source file:com.nineash.hutsync.client.NetworkUtilities.java

private static long getCalendar(Account account) {
    // Find the Last.fm calendar if we've got one
    Uri calenderUri = Calendars.CONTENT_URI.buildUpon()
            .appendQueryParameter(Calendars.ACCOUNT_NAME, account.name)
            .appendQueryParameter(Calendars.ACCOUNT_TYPE, account.type).build();
    Cursor c1 = mContentResolver.query(calenderUri, new String[] { BaseColumns._ID }, null, null, null);
    if (c1.moveToNext()) {
        long ret = c1.getLong(0);
        c1.close();/*from w w  w.  j a  va2 s. co m*/
        return ret;
    } else {
        ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();

        ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(Calendars.CONTENT_URI
                .buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
                .appendQueryParameter(Calendars.ACCOUNT_NAME, account.name)
                .appendQueryParameter(Calendars.ACCOUNT_TYPE, account.type).build());
        builder.withValue(Calendars.ACCOUNT_NAME, account.name);
        builder.withValue(Calendars.ACCOUNT_TYPE, account.type);
        builder.withValue(Calendars.NAME, "Pizza Hut Shifts");
        builder.withValue(Calendars.CALENDAR_DISPLAY_NAME, "Pizza Hut Shifts");
        builder.withValue(Calendars.CALENDAR_COLOR, 0xD51007);
        builder.withValue(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_READ);
        builder.withValue(Calendars.OWNER_ACCOUNT, account.name);
        builder.withValue(Calendars.SYNC_EVENTS, 1);
        operationList.add(builder.build());
        try {
            mContentResolver.applyBatch(CalendarContract.AUTHORITY, operationList);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return -1;
        }
        c1.close();
        return getCalendar(account);
    }
}

From source file:cn.suishen.email.LegacyConversions.java

/**
 * Add a single attachment part to the message
 *
 * This will skip adding attachments if they are already found in the attachments table.
 * The heuristic for this will fail (false-positive) if two identical attachments are
 * included in a single POP3 message.//from  ww  w. j ava2 s.  c om
 * TODO: Fix that, by (elsewhere) simulating an mLocation value based on the attachments
 * position within the list of multipart/mixed elements.  This would make every POP3 attachment
 * unique, and might also simplify the code (since we could just look at the positions, and
 * ignore the filename, etc.)
 *
 * TODO: Take a closer look at encoding and deal with it if necessary.
 *
 * @param context a context for file operations
 * @param localMessage the attachments will be built against this message
 * @param part a single attachment part from POP or IMAP
 * @throws IOException
 */
private static void addOneAttachment(Context context, EmailContent.Message localMessage, Part part)
        throws MessagingException, IOException {

    Attachment localAttachment = new Attachment();

    // Transfer fields from mime format to provider format
    String contentType = MimeUtility.unfoldAndDecode(part.getContentType());
    String name = MimeUtility.getHeaderParameter(contentType, "name");
    if (name == null) {
        String contentDisposition = MimeUtility.unfoldAndDecode(part.getDisposition());
        name = MimeUtility.getHeaderParameter(contentDisposition, "filename");
    }

    // Incoming attachment: Try to pull size from disposition (if not downloaded yet)
    long size = 0;
    String disposition = part.getDisposition();
    if (disposition != null) {
        String s = MimeUtility.getHeaderParameter(disposition, "size");
        if (s != null) {
            size = Long.parseLong(s);
        }
    }

    // Get partId for unloaded IMAP attachments (if any)
    // This is only provided (and used) when we have structure but not the actual attachment
    String[] partIds = part.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA);
    String partId = partIds != null ? partIds[0] : null;

    localAttachment.mFileName = name;
    localAttachment.mMimeType = part.getMimeType();
    localAttachment.mSize = size; // May be reset below if file handled
    localAttachment.mContentId = part.getContentId();
    localAttachment.mContentUri = null; // Will be rewritten by saveAttachmentBody
    localAttachment.mMessageKey = localMessage.mId;
    localAttachment.mLocation = partId;
    localAttachment.mEncoding = "B"; // TODO - convert other known encodings
    localAttachment.mAccountKey = localMessage.mAccountKey;

    if (DEBUG_ATTACHMENTS) {
        Log.d(Logging.LOG_TAG, "Add attachment " + localAttachment);
    }

    // To prevent duplication - do we already have a matching attachment?
    // The fields we'll check for equality are:
    //  mFileName, mMimeType, mContentId, mMessageKey, mLocation
    // NOTE:  This will false-positive if you attach the exact same file, twice, to a POP3
    // message.  We can live with that - you'll get one of the copies.
    Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, localMessage.mId);
    Cursor cursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, null, null, null);
    boolean attachmentFoundInDb = false;
    try {
        while (cursor.moveToNext()) {
            Attachment dbAttachment = new Attachment();
            dbAttachment.restore(cursor);
            // We test each of the fields here (instead of in SQL) because they may be
            // null, or may be strings.
            if (stringNotEqual(dbAttachment.mFileName, localAttachment.mFileName))
                continue;
            if (stringNotEqual(dbAttachment.mMimeType, localAttachment.mMimeType))
                continue;
            if (stringNotEqual(dbAttachment.mContentId, localAttachment.mContentId))
                continue;
            if (stringNotEqual(dbAttachment.mLocation, localAttachment.mLocation))
                continue;
            // We found a match, so use the existing attachment id, and stop looking/looping
            attachmentFoundInDb = true;
            localAttachment.mId = dbAttachment.mId;
            if (DEBUG_ATTACHMENTS) {
                Log.d(Logging.LOG_TAG, "Skipped, found db attachment " + dbAttachment);
            }
            break;
        }
    } finally {
        cursor.close();
    }

    // Save the attachment (so far) in order to obtain an id
    if (!attachmentFoundInDb) {
        localAttachment.save(context);
    }

    // If an attachment body was actually provided, we need to write the file now
    saveAttachmentBody(context, part, localAttachment, localMessage.mAccountKey);

    if (localMessage.mAttachments == null) {
        localMessage.mAttachments = new ArrayList<Attachment>();
    }
    localMessage.mAttachments.add(localAttachment);
    localMessage.mFlagAttachment = true;
}

From source file:at.diamonddogs.util.Utils.java

/**
 * Creates a {@link String} {@link List} from a {@link Cursor}
 *
 * @param cursor the input {@link Cursor}
 * @param name   the name of the colum/*ww  w  .  j av a2  s .c o  m*/
 * @return a {@link String} {@link List}
 */
public static List<String> convertColumnToList(Cursor cursor, String name) {
    List<String> list = new ArrayList<>();
    if (!checkCursor(cursor)) {
        return null;
    }
    cursor.moveToFirst();
    do {
        list.add(cursor.getString(cursor.getColumnIndex(name)));
    } while (cursor.moveToNext());

    return list;
}

From source file:com.android.email_ee.LegacyConversions.java

/**
 * Add a single attachment part to the message
 *
 * This will skip adding attachments if they are already found in the attachments table.
 * The heuristic for this will fail (false-positive) if two identical attachments are
 * included in a single POP3 message.//from  www.j a v  a  2 s . co  m
 * TODO: Fix that, by (elsewhere) simulating an mLocation value based on the attachments
 * position within the list of multipart/mixed elements.  This would make every POP3 attachment
 * unique, and might also simplify the code (since we could just look at the positions, and
 * ignore the filename, etc.)
 *
 * TODO: Take a closer look at encoding and deal with it if necessary.
 *
 * @param context a context for file operations
 * @param localMessage the attachments will be built against this message
 * @param part a single attachment part from POP or IMAP
 * @throws IOException
 */
public static void addOneAttachment(Context context, EmailContent.Message localMessage, Part part)
        throws MessagingException, IOException {

    Attachment localAttachment = new Attachment();

    // Transfer fields from mime format to provider format
    String contentType = MimeUtility.unfoldAndDecode(part.getContentType());
    String name = MimeUtility.getHeaderParameter(contentType, "name");
    if (name == null) {
        String contentDisposition = MimeUtility.unfoldAndDecode(part.getDisposition());
        name = MimeUtility.getHeaderParameter(contentDisposition, "filename");
    }

    // Incoming attachment: Try to pull size from disposition (if not downloaded yet)
    long size = 0;
    String disposition = part.getDisposition();
    if (disposition != null) {
        String s = MimeUtility.getHeaderParameter(disposition, "size");
        if (s != null) {
            size = Long.parseLong(s);
        }
    }

    // Get partId for unloaded IMAP attachments (if any)
    // This is only provided (and used) when we have structure but not the actual attachment
    String[] partIds = part.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA);
    String partId = partIds != null ? partIds[0] : null;

    // Run the mime type through inferMimeType in case we have something generic and can do
    // better using the filename extension
    String mimeType = AttachmentUtilities.inferMimeType(name, part.getMimeType());
    localAttachment.mMimeType = mimeType;
    localAttachment.mFileName = name;
    localAttachment.mSize = size; // May be reset below if file handled
    localAttachment.mContentId = part.getContentId();
    localAttachment.setContentUri(null); // Will be rewritten by saveAttachmentBody
    localAttachment.mMessageKey = localMessage.mId;
    localAttachment.mLocation = partId;
    localAttachment.mEncoding = "B"; // TODO - convert other known encodings
    localAttachment.mAccountKey = localMessage.mAccountKey;

    if (DEBUG_ATTACHMENTS) {
        LogUtils.d(Logging.LOG_TAG, "Add attachment " + localAttachment);
    }

    // To prevent duplication - do we already have a matching attachment?
    // The fields we'll check for equality are:
    //  mFileName, mMimeType, mContentId, mMessageKey, mLocation
    // NOTE:  This will false-positive if you attach the exact same file, twice, to a POP3
    // message.  We can live with that - you'll get one of the copies.
    Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, localMessage.mId);
    Cursor cursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, null, null, null);
    boolean attachmentFoundInDb = false;
    try {
        while (cursor.moveToNext()) {
            Attachment dbAttachment = new Attachment();
            dbAttachment.restore(cursor);
            // We test each of the fields here (instead of in SQL) because they may be
            // null, or may be strings.
            if (stringNotEqual(dbAttachment.mFileName, localAttachment.mFileName))
                continue;
            if (stringNotEqual(dbAttachment.mMimeType, localAttachment.mMimeType))
                continue;
            if (stringNotEqual(dbAttachment.mContentId, localAttachment.mContentId))
                continue;
            if (stringNotEqual(dbAttachment.mLocation, localAttachment.mLocation))
                continue;
            // We found a match, so use the existing attachment id, and stop looking/looping
            attachmentFoundInDb = true;
            localAttachment.mId = dbAttachment.mId;
            if (DEBUG_ATTACHMENTS) {
                LogUtils.d(Logging.LOG_TAG, "Skipped, found db attachment " + dbAttachment);
            }
            break;
        }
    } finally {
        cursor.close();
    }

    // Save the attachment (so far) in order to obtain an id
    if (!attachmentFoundInDb) {
        localAttachment.save(context);
    }

    // If an attachment body was actually provided, we need to write the file now
    saveAttachmentBody(context, part, localAttachment, localMessage.mAccountKey);

    if (localMessage.mAttachments == null) {
        localMessage.mAttachments = new ArrayList<Attachment>();
    }
    localMessage.mAttachments.add(localAttachment);
    localMessage.mFlagAttachment = true;
}

From source file:at.diamonddogs.util.Utils.java

/**
 * Creates a {@link List} from a {@link Cursor}
 *
 * @param <T>             the generic type of the {@link List}
 * @param cursor          the {@link Cursor} to be converted to a {@link List}
 * @param databaseAdapter the {@link DatabaseAdapter} that will be used for conversion
 * @return a {@link List} containing objects created from the input
 * {@link Cursor}//  w w  w  . ja  v  a  2 s.  c  o  m
 */
public static <T> List<T> convertCursorToList(Cursor cursor, DatabaseAdapter<T> databaseAdapter) {
    List<T> list = new ArrayList<>();
    if (!checkCursor(cursor)) {
        return null;
    }
    cursor.moveToFirst();
    do {
        list.add(databaseAdapter.deserialize(cursor));
    } while (cursor.moveToNext());
    return list;
}