Retrieve an Integer from a cursor, or null if an int could not be retrieved. - Android Database

Android examples for Database:Cursor Get

Description

Retrieve an Integer from a cursor, or null if an int could not be retrieved.

Demo Code


import java.util.ArrayList;
import java.util.Locale;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

public class Main{
    /**/*  w w w  . java 2 s. co  m*/
     * Retrieve an Integer from a cursor, or null if an int could not be retrieved.
     *
     * @param cursor The cursor from which to retrieve the value. Must be at a valid position.
     * @param columnIndex The index of the column from which to retrieve the value.
     * @return The Integer value, or null.
     */
    public static Integer safeGetIntFromCursor(Cursor cursor,
            int columnIndex) {
        try {
            return cursor.getInt(columnIndex);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * Retrieve an Integer from a cursor, or null if an int could not be retrieved.
     *
     * @param cursor The cursor from which to retrieve the value. Must be at a valid position.
     * @param columnName The name of the column from which to retrieve the value.
     * @return The Integer value, or null.
     */
    public static Integer safeGetIntFromCursor(Cursor cursor,
            String columnName) {
        return safeGetIntFromCursor(cursor,
                cursor.getColumnIndex(columnName));
    }
    /**
     * Retrieve an int from a cursor, or a default value.
     *
     * @param cursor The cursor from which to retrieve the value. Must be at a valid position.
     * @param columnIndex The index of the column from which to retrieve the value.
     * @param defaultValue The value to return if none was retrieved.
     * @return The int value, or the default.
     */
    public static int safeGetIntFromCursor(Cursor cursor, int columnIndex,
            int defaultValue) {
        try {
            return cursor.getInt(columnIndex);
        } catch (Exception e) {
            e.printStackTrace();
            return defaultValue;
        }
    }
    /**
     * Retrieve an int from a cursor, or a default value.
     *
     * @param cursor The cursor from which to retrieve the value. Must be at a valid position.
     * @param columnName The name of the column from which to retrieve the value.
     * @param defaultValue The value to return if none was retrieved.
     * @return The int value, or the default.
     */
    public static int safeGetIntFromCursor(Cursor cursor,
            String columnName, int defaultValue) {
        return safeGetIntFromCursor(cursor,
                cursor.getColumnIndex(columnName), defaultValue);
    }
}

Related Tutorials