Example usage for android.database Cursor moveToFirst

List of usage examples for android.database Cursor moveToFirst

Introduction

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

Prototype

boolean moveToFirst();

Source Link

Document

Move the cursor to the first row.

Usage

From source file:ro.weednet.contactssync.platform.ContactManager.java

public static void updateContactPhotoHd(Context context, ContentResolver resolver, long rawContactId,
        ContactPhoto photo, BatchOperation batchOperation) {
    final Cursor c = resolver.query(DataQuery.CONTENT_URI, DataQuery.PROJECTION,
            Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "=?",
            new String[] { String.valueOf(rawContactId), Photo.CONTENT_ITEM_TYPE }, null);
    final ContactOperations contactOp = ContactOperations.updateExistingContact(context, rawContactId, true,
            batchOperation);/*from  w w w.  j a v  a2 s  .com*/

    if ((c != null) && c.moveToFirst()) {
        final long id = c.getLong(DataQuery.COLUMN_ID);
        final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, id);
        contactOp.updateAvatar(c.getString(DataQuery.COLUMN_DATA1), photo.getPhotoUrl(), uri);
        c.close();
    } else {
        Log.i(TAG, "creating row, count: " + c.getCount());
        contactOp.addAvatar(photo.getPhotoUrl());
    }
    Log.d(TAG, "updating check timestamp");
    final Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
    contactOp.updateSyncTimestamp1(System.currentTimeMillis(), uri);
}

From source file:com.pdftron.pdf.utils.Utils.java

public static String getUriDisplayName(Context context, Uri contentUri) {
    String displayName = null;/*w  ww  .  j  a va2  s  . com*/
    String[] projection = { OpenableColumns.DISPLAY_NAME };
    Cursor cursor = null;

    if (contentUri.getScheme().equalsIgnoreCase("file")) {
        return contentUri.getLastPathSegment();
    }
    try {
        cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int nameIndex = cursor.getColumnIndexOrThrow(projection[0]);
            if (nameIndex >= 0) {
                displayName = cursor.getString(nameIndex);
            }
        }
    } catch (Exception e) {
        displayName = null;
    }
    if (cursor != null) {
        cursor.close();
    }
    return displayName;
}

From source file:com.almarsoft.GroundhogReader.lib.DBUtils.java

public static void expireReadMessages(Context context, boolean expireAll, long expireTime) {

    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbwrite = db.getWritableDatabase();

    // Get all the expired messages so we can delete bodies and attachments
    long currentTime = System.currentTimeMillis();
    String q = null;/*w ww.  ja  va2 s . c o  m*/

    if (expireAll) {
        q = "SELECT _id, subscribed_group_id, has_attachments, attachments_fnames " + "FROM headers "
                + "WHERE read=1 AND catched=1";
    } else {
        q = "SELECT _id, subscribed_group_id, has_attachments, attachments_fnames " + "FROM headers "
                + "WHERE read=1 AND catched=1 AND read_unixdate < " + currentTime + " - " + expireTime;
    }

    Cursor c = dbwrite.rawQuery(q, null);

    int count = c.getCount();
    c.moveToFirst();
    String groupname;

    for (int i = 0; i < count; i++) {

        groupname = getGroupNameFromId(c.getInt(1) /*subscribed_group_id*/, context);
        FSUtils.deleteCacheMessage(c.getInt(0)/* _id */, groupname);

        if (c.getInt(2)/*has_attach*/ == 1) {
            FSUtils.deleteAttachments(c.getString(3) /*attachments_fnames*/, groupname);
        }

        c.moveToNext();
    }

    if (expireAll)
        q = "DELETE FROM headers WHERE read=1";
    else
        q = "DELETE FROM headers WHERE read=1 AND read_unixdate < " + currentTime + " - " + expireTime;
    dbwrite.execSQL(q);
    c.close();
    dbwrite.close();
    db.close();
}

From source file:com.almarsoft.GroundhogReader.lib.DBUtils.java

public static Vector<Object> isHeaderInDatabase(Long number, String group, Context context) {
    int groupid = getGroupIdFromName(group, context);

    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbread = db.getReadableDatabase();
    Vector<Object> retVal = null;

    String q = "SELECT _id, server_article_id FROM headers WHERE subscribed_group_id=" + groupid
            + " AND server_article_number=" + number;
    Cursor c = dbread.rawQuery(q, null);
    int count = c.getCount();

    if (count > 0) {
        c.moveToFirst();
        retVal = new Vector<Object>(2);
        retVal.add(c.getLong(0));//from w  w  w .  ja  v  a  2 s  .  c  o  m
        retVal.add(c.getString(1));
    }

    c.close();
    dbread.close();
    db.close();

    return retVal;
}

From source file:com.android.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  .ja v a  2 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
 * @param upgrading true if upgrading a local account - handle attachments differently
 * @throws IOException
 */
private static void addOneAttachment(Context context, EmailContent.Message localMessage, Part part,
        boolean upgrading) 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");
    }

    // Select the URI for the new attachments.  For attachments downloaded by the legacy
    // IMAP/POP code, this is not determined yet, so is null (it will be rewritten below,
    // or later, when the actual attachment file is created.)
    //
    // When upgrading older local accounts, the URI represents a local asset (e.g. a photo)
    // so we need to preserve the URI.
    // TODO This works for outgoing messages, where the URI does not change.  May need
    // additional logic to handle the case of rewriting URI for received attachments.
    Uri contentUri = null;
    String contentUriString = null;
    if (upgrading) {
        Body body = part.getBody();
        if (body instanceof LocalStore.LocalAttachmentBody) {
            LocalStore.LocalAttachmentBody localBody = (LocalStore.LocalAttachmentBody) body;
            contentUri = localBody.getContentUri();
            if (contentUri != null) {
                contentUriString = contentUri.toString();
            }
        }
    }

    // Find size, if available, via a number of techniques:
    long size = 0;
    if (upgrading) {
        // If upgrading a legacy account, the size must be recaptured from the data source
        if (contentUri != null) {
            Cursor metadataCursor = context.getContentResolver().query(contentUri,
                    ATTACHMENT_META_COLUMNS_PROJECTION, null, null, null);
            if (metadataCursor != null) {
                try {
                    if (metadataCursor.moveToFirst()) {
                        size = metadataCursor.getInt(ATTACHMENT_META_COLUMNS_SIZE);
                    }
                } finally {
                    metadataCursor.close();
                }
            }
        }
        // TODO: a downloaded legacy attachment - see if the above code works
    } else {
        // Incoming attachment: Try to pull size from disposition (if not downloaded yet)
        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 = contentUriString;
    localAttachment.mMessageKey = localMessage.mId;
    localAttachment.mLocation = partId;
    localAttachment.mEncoding = "B"; // TODO - convert other known encodings

    if (DEBUG_ATTACHMENTS) {
        Log.d(Email.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().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(Email.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
    if (!upgrading) {
        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:mil.nga.giat.mage.sdk.utils.MediaUtility.java

public static String getFileAbsolutePath(Uri uri, Context c) {
    String fileName = null;/*from   w  ww  .  j a va 2 s .c om*/
    String scheme = uri.getScheme();
    if (scheme.equals("file")) {
        fileName = uri.getPath();
    } else if (scheme.equals("content")) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = c.getContentResolver().query(uri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            Log.e(LOG_NAME, "Error reading content URI", e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    return fileName;
}

From source file:Main.java

/**
 * Retourner la liste des calendriers// www  .  j  a v  a2s .c  om
 * 
 * @return Liste des calendriers
 */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Map<Integer, String> getCalendars(ContentResolver contentResolver) {
    Map<Integer, String> calendars = new HashMap<Integer, String>();
    String[] projection;
    Uri calendarUri;
    Cursor cursor;
    String accessLevelCol;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        calendarUri = CalendarContract.Calendars.CONTENT_URI;
        projection = new String[] { CalendarContract.Calendars._ID,
                CalendarContract.Calendars.CALENDAR_DISPLAY_NAME };
        accessLevelCol = CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL;
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
        calendarUri = Uri.parse("content://com.android.calendar/calendars");
        projection = new String[] { "_id", "displayname" };
        accessLevelCol = "ACCESS_LEVEL";
    } else {
        calendarUri = Uri.parse("content://calendar/calendars");
        projection = new String[] { "_id", "displayname" };
        accessLevelCol = "ACCESS_LEVEL";
    }

    cursor = contentResolver.query(calendarUri, projection, accessLevelCol + "=700", null, null);

    if (cursor != null && cursor.moveToFirst()) {
        while (cursor.isAfterLast() == false) {
            calendars.put(cursor.getInt(0), cursor.getString(1));
            cursor.moveToNext();
        }
        cursor.close();
    }

    return calendars;
}

From source file:com.almarsoft.GroundhogReader.lib.DBUtils.java

public static Vector<Long> getUnreadNoncatchedArticleList(String group, Context context) {
    int groupid = getGroupIdFromName(group, context);

    Vector<Long> artList = null;
    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbread = db.getReadableDatabase();

    String q = "SELECT server_article_number FROM headers WHERE subscribed_group_id=" + groupid
            + " AND read=0 AND catched=0";
    Cursor c = dbread.rawQuery(q, null);

    int count = c.getCount();
    artList = new Vector<Long>(count);

    c.moveToFirst();

    for (int i = 0; i < count; i++) {
        artList.add(c.getLong(0));/*from  w ww .jav a 2 s  . c o m*/
        c.moveToNext();
    }

    c.close();
    dbread.close();
    db.close();
    return artList;
}

From source file:com.almarsoft.GroundhogReader.lib.DBUtils.java

public static HashSet<String> getGroupSentMessagesSet(String group, Context context) {
    int groupid = getGroupIdFromName(group, context);

    HashSet<String> retVal = null;
    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbread = db.getReadableDatabase();

    String q = "SELECT server_article_id FROM sent_posts_log WHERE subscribed_group_id=" + groupid;
    Cursor c = dbread.rawQuery(q, null);
    int count = c.getCount();

    retVal = new HashSet<String>(count);
    c.moveToFirst();

    for (int i = 0; i < count; i++) {
        retVal.add(c.getString(0));// ww  w .j  av a 2s  .c  o  m
        c.moveToNext();
    }

    c.close();
    dbread.close();
    db.close();

    return retVal;
}

From source file:com.jpa.JPAApplication.java

public void setDbAuth() {
    DbModel db = new DbModel(getApplicationContext());
    db.open();//from  w  w  w  .  jav a 2  s  . co m

    Cursor c = db.fetch();

    if (c.moveToFirst() == false) {
        db.insert(this.getString(R.string.jpa_default_url), this.getString(R.string.jpa_default_password));
    }

    db.close();
}