Reputation: 5995
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
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