Jack M
Jack M

Reputation: 5995

Can't get any data back from SQLite

I wrote this simple Activity to test writing and reading from an SQLite database on Android.

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);     
        DatabaseHelper db = new DatabaseHelper(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private class DatabaseHelper extends SQLiteOpenHelper
    {

        public DatabaseHelper(Context context) {
            super(context, "TestDatabase", null, 3);
            getWritableDatabase().rawQuery("INSERT INTO TestTable VALUES ('Apple')", null);
            Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM TestTable", null);
            Log.d("trace", String.valueOf(cursor.moveToFirst()));
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE TestTable (value text)");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS TestTable");
            onCreate(db);
        }

    }

}

The meat of it is in the DatabaseHelper constructor, where I write a value to TestTable, try to get it back in a cursor, and then log the value of cursor.moveToFirst() (which should only be false if the cursor is empty). It's false. What's going on?

Upvotes: 0

Views: 85

Answers (2)

Chaojun
Chaojun

Reputation: 1

1) rawQuery() should be changed to execSQL like following line:

    public DatabaseHelper(Context context) {
        super(context, "TestDatabase", null, 3);

        getWritableDatabase().execSQL("INSERT INTO TestTable VALUES ('Apple')");
        Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM TestTable", null);
        Log.d("trace:", String.valueOf(cursor.moveToFirst()));
    }

2) in order to make sure call onCreate(), override onDowngrade() in your DatabaseHelper class:

    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS TestTable");
        onCreate(db);
    } 

Upvotes: 0

Luke
Luke

Reputation: 2599

The documentation says

rawQuery runs the provided SQL and returns a Cursor over the result set.

Since then, you should not use it for INSERT. Try execSQL or insert for getting the row id of the inserted row.

Upvotes: 1

Related Questions