thenry
thenry

Reputation: 368

read data from SQLite database using AsyncTask on button press

Not very familiar with SQLite databases but I've gone through some tutorials/SO posts and I can't figure out what I am doing wrong. Currently I want to save data on a button press and then read the data onto another activity in table form.

Here is my attempt at creating the database:

public class DBHelper extends SQLiteOpenHelper {
    private final static int    DB_VERSION = 10;
    static final String DATABASE_NAME = "workout.db";
    public static final String TABLE_NAME = "Workout_Log";
    public static final String COLUMN_DISTANCE = "Distance";
    public static final String COLUMN_SPEED = "Speed";
    public static final String COLUMN_DURATION = "Duration";

public static final String SQL_CREATE_WORKOUT_TABLE = "CREATE TABLE " + TABLE_NAME + "(" +
        BaseColumns._ID + " INTEGER PRIMARY KEY," +
        COLUMN_DISTANCE + " REAL NOT NULL, " +
        COLUMN_SPEED + " REAL NOT NULL, " +
        COLUMN_DURATION + " REAL NOT NULL );";

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null,DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    sqLiteDatabase.execSQL(SQL_CREATE_WORKOUT_TABLE);
}

Here is where I save the data on button press:

   private class WriteToDB extends AsyncTask<Void, Void, Void>{
        @Override
        protected Void doInBackground(Void... params) {
            DBHelper dbHelper = new DBHelper(getBaseContext());
            // Gets the data repository in write mode
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            try {
                // Create a new map of values, where column names are the keys
                ContentValues values = new ContentValues();
                values.put(DBHelper.COLUMN_DISTANCE, distance);
                values.put(DBHelper.COLUMN_CADENCE, roundedLeft + roundedRight);
                values.put(DBHelper.COLUMN_DURATION, leftTime + rightTime);
            } finally {
                    db.close();
            }
            return null;
        }
    }

While calling the Async function in my onClickListener:

//Saves on Click?
                    WriteToDB writeToDB = new WriteToDB();
                    writeToDB.execute();

I believe it is saved, correct me if I'm wrong, so I try to read and set a TextView to the value in the database(to check if it works):

private class ReadFromDB extends AsyncTask<Void, Void, Void>{
        @Override
        protected Void doInBackground(Void... params) {
            DBHelper dbHelper = new DBHelper(getBaseContext());
            // Gets the data repository in write mode
            SQLiteDatabase db = dbHelper.getReadableDatabase();

            String[] projection = {
                    BaseColumns._ID,
                    DBHelper.COLUMN_DISTANCE,
                    DBHelper.COLUMN_CADENCE,
                    DBHelper.COLUMN_DURATION
            };

            Cursor cursor = db.query(
                    DBHelper.TABLE_NAME,
                    projection,
                    null,
                    null,
                    null,
                    null,
                    null
            );
            cursor.moveToFirst();
            float itemId = cursor.getFloat(
                    cursor.getColumnIndexOrThrow(DBHelper.COLUMN_DISTANCE)
            );
            val = Float.toString(itemId);
            cursor.close();

            return null;
        }
    }

When I press the button to access it I get an error:

Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

Any suggestions?

Upvotes: 0

Views: 4269

Answers (1)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132982

In doInBackground just preparing ContentValues for inserting in db but not calling SQLiteDatabase.insert method for adding new row in database:

long rowID=db.insert(DBHelper.TABLE_NAME, null, values);

And on Button press getting :

Caused by: android.database.CursorIndexOutOfBoundsException

Error because cursor is empty.

To avoid this error use Cursor.getCount() to check Cursor object contains rows or not before reading from it.

Upvotes: 2

Related Questions