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:com.amarinfingroup.net.utilities.EncryptionUtils.java

/**
 * Retrieve the encryption information for this uri.
 *
 * @param mUri either an instance URI (if previously saved) or a form URI
 * @param instanceMetadata//from w  w w .j a v  a 2 s  . c  o  m
 * @return
 */
public static EncryptedFormInformation getEncryptedFormInformation(Uri mUri,
        InstanceMetadata instanceMetadata) {

    ContentResolver cr = Collect.getInstance().getContentResolver();

    // fetch the form information
    String formId;
    String formVersion;
    PublicKey pk;
    Base64Wrapper wrapper;

    Cursor formCursor = null;
    try {
        if (cr.getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) {
            // chain back to the Form record...
            String[] selectionArgs = null;
            String selection = null;
            Cursor instanceCursor = null;
            try {
                instanceCursor = cr.query(mUri, null, null, null, null);
                if (instanceCursor.getCount() != 1) {
                    Log.e(t, "Not exactly one record for this instance!");
                    return null; // save unencrypted.
                }
                instanceCursor.moveToFirst();
                String jrFormId = instanceCursor
                        .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
                int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION);
                if (!instanceCursor.isNull(idxJrVersion)) {
                    selectionArgs = new String[] { jrFormId, instanceCursor.getString(idxJrVersion) };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + "=?";
                } else {
                    selectionArgs = new String[] { jrFormId };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + " IS NULL";
                }
            } finally {
                if (instanceCursor != null) {
                    instanceCursor.close();
                }
            }

            formCursor = cr.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs, null);

            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form matches this jr_form_id");
                return null; // save unencrypted
            }
            formCursor.moveToFirst();
        } else if (cr.getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) {
            formCursor = cr.query(mUri, null, null, null, null);
            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form!");
                return null; // save unencrypted.
            }
            formCursor.moveToFirst();
        }

        formId = formCursor.getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID));
        if (formId == null || formId.length() == 0) {
            Log.e(t, "No FormId specified???");
            return null;
        }
        int idxVersion = formCursor.getColumnIndex(FormsColumns.JR_VERSION);
        int idxBase64RsaPublicKey = formCursor.getColumnIndex(FormsColumns.BASE64_RSA_PUBLIC_KEY);
        formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion);
        String base64RsaPublicKey = formCursor.isNull(idxBase64RsaPublicKey) ? null
                : formCursor.getString(idxBase64RsaPublicKey);

        if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
            return null; // this is legitimately not an encrypted form
        }

        int version = android.os.Build.VERSION.SDK_INT;
        if (version < 8) {
            Log.e(t, "Phone does not support encryption.");
            return null; // save unencrypted
        }

        // this constructor will throw an exception if we are not
        // running on version 8 or above (if Base64 is not found).
        try {
            wrapper = new Base64Wrapper();
        } catch (ClassNotFoundException e) {
            Log.e(t, "Phone does not have Base64 class but API level is " + version);
            e.printStackTrace();
            return null; // save unencrypted
        }

        // OK -- Base64 decode (requires API Version 8 or higher)
        byte[] publicKey = wrapper.decode(base64RsaPublicKey);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf;
        try {
            kf = KeyFactory.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            Log.e(t, "Phone does not support RSA encryption.");
            e.printStackTrace();
            return null;
        }
        try {
            pk = kf.generatePublic(publicKeySpec);
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
            Log.e(t, "Invalid RSA public key.");
            return null;
        }
    } finally {
        if (formCursor != null) {
            formCursor.close();
        }
    }

    // submission must have an OpenRosa metadata block with a non-null
    // instanceID value.
    if (instanceMetadata.instanceId == null) {
        Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block");
        return null;
    }

    // For now, prevent encryption if the BouncyCastle implementation is not present.
    // https://code.google.com/p/opendatakit/issues/detail?id=918
    try {
        Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, ENCRYPTION_PROVIDER);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for padding implementation of symmetric algorithm!");
        return null;
    }

    return new EncryptedFormInformation(formId, formVersion, instanceMetadata, pk, wrapper);
}

From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java

/**
 * Get display name from the uri//from   w w w  .  ja  va 2  s  .  c  o  m
 *
 * @param context
 * @param uri
 * @return
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getDisplayName(Context context, Uri uri) {

    String name = null;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        ContentResolver resolver = context.getContentResolver();
        Cursor nameCursor = resolver.query(uri, null, null, null, null);
        try {
            if (nameCursor.getCount() > 0) {
                int displayNameIndex = nameCursor
                        .getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME);
                if (displayNameIndex >= 0 && nameCursor.moveToFirst()) {
                    name = nameCursor.getString(displayNameIndex);
                }
            }
        } finally {
            nameCursor.close();
        }
    }

    return name;
}

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

public static void banUser(String decodedfrom, Context context) {
    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbwrite = db.getWritableDatabase();

    Cursor c = dbwrite.rawQuery("SELECT _id FROM banned_users " + " WHERE name=" + esc(decodedfrom), null);

    if (c.getCount() > 0) {
        c.moveToFirst();
        dbwrite.execSQL("UPDATE banned_users SET bandisabled=0 WHERE _id=" + c.getInt(0));
    } else {//ww  w  . j ava2  s.  c o m
        ContentValues cv = new ContentValues();
        cv.put("name", decodedfrom);
        cv.put("bandisabled", 0);
        dbwrite.insert("banned_users", null, cv);
    }

    // Mark all the user posts as read, so they get deleted later
    dbwrite.execSQL("UPDATE headers SET read=1, read_unixdate=" + System.currentTimeMillis()
            + " WHERE from_header=" + esc(decodedfrom));

    c.close();
    dbwrite.close();
    db.close();
}

From source file:cd.education.data.collector.android.utilities.EncryptionUtils.java

/**
 * Retrieve the encryption information for this uri.
 *
 * @param mUri either an instance URI (if previously saved) or a form URI
 * @param instanceMetadata/*  w  w w  .  j a  v a 2s .com*/
 * @return
 */
public static EncryptedFormInformation getEncryptedFormInformation(Uri mUri,
        FormController.InstanceMetadata instanceMetadata) {

    ContentResolver cr = Collect.getInstance().getContentResolver();

    // fetch the form information
    String formId;
    String formVersion;
    PublicKey pk;
    Base64Wrapper wrapper;

    Cursor formCursor = null;
    try {
        if (cr.getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) {
            // chain back to the Form record...
            String[] selectionArgs = null;
            String selection = null;
            Cursor instanceCursor = null;
            try {
                instanceCursor = cr.query(mUri, null, null, null, null);
                if (instanceCursor.getCount() != 1) {
                    Log.e(t, "Not exactly one record for this instance!");
                    return null; // save unencrypted.
                }
                instanceCursor.moveToFirst();
                String jrFormId = instanceCursor
                        .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
                int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION);
                if (!instanceCursor.isNull(idxJrVersion)) {
                    selectionArgs = new String[] { jrFormId, instanceCursor.getString(idxJrVersion) };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + "=?";
                } else {
                    selectionArgs = new String[] { jrFormId };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + " IS NULL";
                }
            } finally {
                if (instanceCursor != null) {
                    instanceCursor.close();
                }
            }

            formCursor = cr.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs, null);

            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form matches this jr_form_id");
                return null; // save unencrypted
            }
            formCursor.moveToFirst();
        } else if (cr.getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) {
            formCursor = cr.query(mUri, null, null, null, null);
            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form!");
                return null; // save unencrypted.
            }
            formCursor.moveToFirst();
        }

        formId = formCursor.getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID));
        if (formId == null || formId.length() == 0) {
            Log.e(t, "No FormId specified???");
            return null;
        }
        int idxVersion = formCursor.getColumnIndex(FormsColumns.JR_VERSION);
        int idxBase64RsaPublicKey = formCursor.getColumnIndex(FormsColumns.BASE64_RSA_PUBLIC_KEY);
        formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion);
        String base64RsaPublicKey = formCursor.isNull(idxBase64RsaPublicKey) ? null
                : formCursor.getString(idxBase64RsaPublicKey);

        if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
            return null; // this is legitimately not an encrypted form
        }

        int version = android.os.Build.VERSION.SDK_INT;
        if (version < 8) {
            Log.e(t, "Phone does not support encryption.");
            return null; // save unencrypted
        }

        // this constructor will throw an exception if we are not
        // running on version 8 or above (if Base64 is not found).
        try {
            wrapper = new Base64Wrapper();
        } catch (ClassNotFoundException e) {
            Log.e(t, "Phone does not have Base64 class but API level is " + version);
            e.printStackTrace();
            return null; // save unencrypted
        }

        // OK -- Base64 decode (requires API Version 8 or higher)
        byte[] publicKey = wrapper.decode(base64RsaPublicKey);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf;
        try {
            kf = KeyFactory.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            Log.e(t, "Phone does not support RSA encryption.");
            e.printStackTrace();
            return null;
        }
        try {
            pk = kf.generatePublic(publicKeySpec);
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
            Log.e(t, "Invalid RSA public key.");
            return null;
        }
    } finally {
        if (formCursor != null) {
            formCursor.close();
        }
    }

    // submission must have an OpenRosa metadata block with a non-null
    // instanceID value.
    if (instanceMetadata.instanceId == null) {
        Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block");
        return null;
    }

    // For now, prevent encryption if the BouncyCastle implementation is not present.
    // https://code.google.com/p/opendatakit/issues/detail?id=918
    try {
        Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, ENCRYPTION_PROVIDER);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for padding implementation of symmetric algorithm!");
        return null;
    }

    return new EncryptedFormInformation(formId, formVersion, instanceMetadata, pk, wrapper);
}

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

public static HashSet<String> getBannedThreads(String group, Context context) {

    HashSet<String> bannedThreads = null;

    int groupid = getGroupIdFromName(group, context);

    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbread = db.getReadableDatabase();

    String q = "SELECT clean_subject FROM banned_threads WHERE subscribed_group_id=" + groupid
            + " AND bandisabled=0";

    Cursor c = dbread.rawQuery(q, null);
    if (c.getCount() > 0) {

        bannedThreads = new HashSet<String>(c.getCount());
        c.moveToFirst();

        int count = c.getCount();
        for (int i = 0; i < count; i++) {
            bannedThreads.add(c.getString(0));
            c.moveToNext();//from   www . ja  va  2s  .c o m
        }
    }

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

    if (bannedThreads == null)
        bannedThreads = new HashSet<String>(0);
    return bannedThreads;
}

From source file:com.pheromone.plugins.FileUtils.java

/**
 * Queries the media store to find out what the file path is for the Uri we supply
 *
 * @param contentUri the Uri of the audio/image/video
 * @param ctx the current applicaiton context
 * @return the full path to the file//w  ww  . j a v  a  2 s.com
 */
protected static String getRealPathFromURI(Uri contentUri, PhonegapActivity ctx) {
    String[] proj = { _DATA };
    Cursor cursor = ctx.managedQuery(contentUri, proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(_DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

From source file:com.andrewshu.android.reddit.common.Common.java

public static boolean isClicked(Context context, String url) {
    Cursor cursor;
    try {//from   w  w w .  j av a2  s  .  c  o m
        cursor = context.getContentResolver().query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION,
                Browser.HISTORY_PROJECTION[Browser.HISTORY_PROJECTION_URL_INDEX] + "=?", new String[] { url },
                null);
    } catch (Exception ex) {
        if (Constants.LOGGING)
            Log.w(TAG, "Error querying Android Browser for history; manually revoked permission?", ex);
        return false;
    }

    if (cursor != null) {
        boolean isClicked = cursor.moveToFirst(); // returns true if cursor is not empty
        cursor.close();
        return isClicked;
    } else {
        return false;
    }
}

From source file:com.android.emailcommon.provider.Account.java

/**
 * Return the id of the default account. If one hasn't been explicitly specified, return the
 * first one in the database. If no account exists, returns {@link #NO_ACCOUNT}.
 *
 * @param context the caller's context/* w w  w.j a  v  a2  s .c om*/
 * @param lastUsedAccountId the last used account id, which is the basis of the default account
 */
public static long getDefaultAccountId(final Context context, final long lastUsedAccountId) {
    final Cursor cursor = context.getContentResolver().query(CONTENT_URI, ID_PROJECTION, null, null, null);

    long firstAccount = NO_ACCOUNT;

    try {
        if (cursor != null && cursor.moveToFirst()) {
            do {
                final long accountId = cursor.getLong(Account.ID_PROJECTION_COLUMN);

                if (accountId == lastUsedAccountId) {
                    return accountId;
                }

                if (firstAccount == NO_ACCOUNT) {
                    firstAccount = accountId;
                }
            } while (cursor.moveToNext());
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    return firstAccount;
}

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

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

    HashSet<String> readSet = null;

    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbread = db.getReadableDatabase();

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

    if (count > 0) {
        readSet = new HashSet<String>(c.getCount());
        c.moveToFirst();

        for (int i = 0; i < count; i++) {
            readSet.add(c.getString(0));
            c.moveToNext();/*from www  . j a v a2 s. c om*/
        }
    }

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

    if (readSet == null)
        readSet = new HashSet<String>(0);
    return readSet;
}

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

public static HashSet<String> getFavoriteAuthors(Context context) {

    HashSet<String> favoriteAuthors = null;

    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbread = db.getReadableDatabase();

    Cursor c = dbread.rawQuery("SELECT name FROM favorite_users", null);
    if (c.getCount() > 0) {
        favoriteAuthors = new HashSet<String>(c.getCount());
        c.moveToFirst();

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

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

    if (favoriteAuthors == null)
        favoriteAuthors = new HashSet<String>(0);
    return favoriteAuthors;
}