Retrieve a String from a cursor, or null. - Android Database

Android examples for Database:Cursor Get

Description

Retrieve a String from a cursor, or null.

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  . ja  v  a  2s.com
     * Retrieve a String from a cursor, or null.
     *
     * @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 String value, or null.
     */
    public static String safeGetStringFromCursor(Cursor cursor,
            int columnIndex) {
        try {
            return cursor.getString(columnIndex);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * Retrieve a String from a cursor, or null if a String 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 String value, or null.
     */
    public static String safeGetStringFromCursor(Cursor cursor,
            String columnName) {
        return safeGetStringFromCursor(cursor,
                cursor.getColumnIndex(columnName));
    }
    /**
     * Retrieve a String 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 String value, or null.
     */
    public static String safeGetStringFromCursor(Cursor cursor,
            int columnIndex, String defaultValue) {
        try {
            return cursor.getString(columnIndex);
        } catch (Exception e) {
            e.printStackTrace();
            return defaultValue;
        }
    }
    /**
     * Retrieve a String 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 String value, or the default.
     */
    public static String safeGetStringFromCursor(Cursor cursor,
            String columnName, String defaultValue) {
        return safeGetStringFromCursor(cursor,
                cursor.getColumnIndex(columnName), defaultValue);
    }
}

Related Tutorials