I\'m developing an expense tracker where I want to populate the DB with a few records when the application first start. I tried to call the method in my splash activity and add
try to add a flag in your user preferences
/shared preferences
to check the apps first run and then upon return you can decide if you want to create your db or read it !
have a look here http://www.vogella.com/articles/AndroidSQLite/article.html
EDIT
or just check if dbexists instead of user pref flag
Make a habit of formatting your code well. The last column definition does not have a comma :
String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER
+ "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_NAME + " TEXT, "
+ KEY_EMAIL + " TEXT, "
+ KEY_PW + " TEXT, "
+ KEY_SESSION + " INTEGER "
+ ")";
String CREATE_EXPENSE_TYPE_TABLE = "CREATE TABLE " + TABLE_EXPENSE_TYPE
+ "("
+ KEY_EXPENSE_ID + " INTEGER AUTOINCREMENT, "
+ KEY_EXPENSE_TYPE + " TEXT PRIMARY KEY "
+ ")";
private final String SAMPLE_DB_NAME = "TheftData";
private final String SAMPLE_TABLE_NAME = "UserDetails";
String CreateTable = "CREATE TABLE IF NOT EXISTS " +
SAMPLE_TABLE_NAME +
" (Username VARCHAR, Password VARCHAR," +
" );";
Then in onCreate
protected void onCreate(Bundle savedInstanceState) {
try {
sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
sampleDB.execSQL(CreateTable);
sampleDB.close();
}
catch(Exception e)
{Toast.makeText(getApplicationContext(), " Error: "+e.getMessage(), Toast.LENGTH_LONG).show();
sampleDB.close();
}
and to add data
public void insertData(String username,String password)
{
sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
sampleDB.execSQL(CreateTable);
sampleDB.execSQL("INSERT INTO " +
SAMPLE_TABLE_NAME +
" Values ('"+username+"','"+ password+"');");
sampleDB.close();
}
android.database.sqlite.SQLiteException: no such column: exp_type (code 1): , while compiling: SELECT * FROM expense_type Order BY exp_type DESC
This is your error:
String CREATE_EXPENSE_TYPE_TABLE = "CREATE TABLE " + TABLE_EXPENSE_TYPE
+ " (" + KEY_EXPENSE_ID + " INTEGER AUTOINCREMENT" +
KEY_EXPENSE_TYPE + " TEXT PRIMARY KEY" + ")
You need a space after INTEGER AUTOINCREMENT
KEY_EXPENSE_ID + " INTEGER AUTOINCREMENT" +
KEY_EXPENSE_TYPE
evaluates to:
"id integer autoincrementexp_type"