按下按钮,使用AsyncTask从SQLite数据库中读取数据

时间:2016-07-20 18:11:05

标签: android sqlite android-asynctask

对SQLite数据库不是很熟悉,但我已经完成了一些教程/ SO帖子,但我无法弄清楚我做错了什么。目前我想在按下按钮时保存数据,然后以表格形式将数据读取到另一个活动上。

以下是我创建数据库的尝试:

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);
}

这是我在按下按钮时保存数据的地方:

   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;
        }
    }

在我的onClickListener中调用Async函数时:

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

我相信它已保存,如果我错了,请更正我,所以我尝试读取并将TextView设置为数据库中的值(以检查它是否有效):

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;
        }
    }

当我按下按钮进入时,我收到一个错误:

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

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

doInBackground中只准备ContentValues插入数据库但不调用SQLiteDatabase.insert方法在数据库中添加新行:

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

按下按钮获取:

Caused by: android.database.CursorIndexOutOfBoundsException

错误,因为cursor为空。

要避免此错误,请使用Cursor.getCount()在读取之前检查Cursor对象是否包含行。