I downloaded a simple login page code in zip file from
http://bit.ly/saket_github_loginpage.
Please check this application and tell me where the database file is. And how can I see this? I also want to create some new tables. How can I do this? I have tried getting it to work with the following code:
public class DbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "saket.db";
private static final int DATABASE_VERSION = 1;
public static final String SAKET_TABLE_NAME = "login";
public static final String SAKET_TABLE_NAME1 = "Employee";
private static final String SAKET_TABLE_CREATE =
"CREATE TABLE " + SAKET_TABLE_NAME + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"username TEXT NOT NULL, password TEXT NOT NULL, email TEXT NO TNULL);";
private static final String SAKET_TABLE_CREATE1 =
"CREATE TABLE " + SAKET_TABLE_NAME1 + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
"name TEXT NOT NULL, Address TEXT NOT NULL, email TEXT NOT NULL);";
private static final String SAKET_DB_ADMIN = "INSERT INTO" +
SAKET_TABLE_NAME+"values(1, admin, password, admin#gmail.com);";
private static final String SAKET_DB_ADMIN1 = "INSERT INTO " +
SAKET_TABLE_NAME+"values(2, emp, password, Emp#gmail.com);";
private static final String SAKET_DB_ADMIN2 = "INSERT INTO " +
SAKET_TABLE_NAME1 + "values(1, mahesh, address, mahesh#gmail.com);";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
System.out.println("In constructor");
}
}
It's better you check on emulator, or a rooted device....... Follow these steps
In emulator run your application.
In eclipse go to Window>Show view>Other...>Android and click file explorer
In File explorer find a folder called data which should not be on your SD card
in data>data>your.application.packagename you can find database folder, your database is there
Find an icon called pull a file from device...... you can copy that database anywhere you like using this button....
There are many clients to view and operate the SQLITE database including firefox has one..... I recommend to use this.... If you are on ubuntu they have a good application in their software center..... [I don't remember the name so apologies for that]
I hope this works for you....
1)You can see your database in file explorer. you can refer to file explorer as
Window -> show view -> other -> Select File Explorer.
in File Explorer goto
data -> data -> com.YourApplicationPackage -> YourDatabase
2)To create new table is by SQL use CREATE query having stored in String Constant and the execute it by your SQLite database object. if your sqlite database object is db then it would be db.execSQL(StringConstant); String constant carries your SQL CREATE query...
I hope you got your answer....
Related
I'm getting this error -
07-03 12:29:18.643: E/SQLiteLog(5181): (1) table accounts has no column named otherNotes
This is my code:
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "accountsManager";
private static final String TABLE_ACCOUNTS = "accounts";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_USERID = "userId";
private static final String KEY_PASSWORD = "password";
private static final String KEY_LOGINURL = "loginUrl";
private static final String KEY_OTHERNOTES = "otherNotes";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_ACCOUNTS_TABLE = "CREATE TABLE " + TABLE_ACCOUNTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_USERID + " TEXT," + KEY_PASSWORD + " TEXT," + KEY_LOGINURL + " TEXT,"
+ KEY_OTHERNOTES + " TEXT" + ");";
db.execSQL(CREATE_ACCOUNTS_TABLE);
}
public void addAccount(AccountDetails account) {
SQLiteDatabase db = this.getWritableDatabase();
System.out.println("Hello!");
ContentValues values = new ContentValues();
values.put(KEY_TITLE, account.getTitle()); // Account Title
values.put(KEY_USERID, account.getUserId()); // account userid
values.put(KEY_PASSWORD, account.getPassword()); // account password
values.put(KEY_LOGINURL, account.getLoginUrl()); // account loginurl
values.put(KEY_OTHERNOTES, account.getOtherNotes()); // account othernotes
Log.v("title", KEY_TITLE);
// Inserting Row
db.insert(TABLE_ACCOUNTS, null, values);
db.close(); // Closing database connection
}
Also, when I remove the following statement:
values.put(KEY_OTHERNOTES, account.getOtherNotes()); // account othernotes
Then I get the same problem with password...etc.
i.e, (1) table accounts has no column named password
Please help!!
It seems that you added some columns later in the database. I do agree with Ken Wolf and you should consider uninstalling and re-installing your app. One better approach is, drop and recreate all tables in onUpdate method, and increase the db version every time you change the schema.
Well, If you are confindent about syntax for creating table, than it may happen
when you add new column in your same table, for that...
1) Unistall from your device and run it again.
OR
2) Setting -> app -> ClearData
OR
3) Change DATABASE_NAME in your "DatabaseHandler" class
( I faced same problem. But I suuceed by changing DATABASE_NAME.)
OR
4) Change DATABASE_VERSION in your "DatabaseHandler" class
(If you have added new column than it will upgrade autimatically)
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
As Benil says in a comment above, change the database version number and run the code again.
The SQL code looks fine.
I think that you forgot to call open() on your database object that you created.
add this methods to you SQL class:
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public DataBaseMain open() throws SQLException{
// Open the database to make her writeable, must be called before writing
// to database
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
// Closing the database for writing, avoids error.
ourHelper.close();
}
And use when you want to call you DB.
Try "Clear Data " of your App from Settings.
For me this problem was occuring because i was storage data on SD Card and later i added some columns.
So if you are saving on SD card delete the previous data.
For those who have similar problem and above solution is not worked then check 2 things:
Space between column name and data type like
COLUMN_NUMBER+" TEXT PRIMARY KEY) not COLUMN_NUMBER+"TEXT PRIMARY KEY)
The order of column during the creation of table should same as map for data insertion like
ContentValues values = new ContentValues();
values.put(TEST_ID, testId);
values.put(CLASS_NAME, className);
values.put(SUBJECT, subject);
"CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ TEST_ID + " INTEGER,"
+ CLASS_NAME + " TEXT,"
+ SUBJECT + " TEXT,"
Here It is your query..TRY this.
String CREATE_ACCOUNTS_TABLE = "CREATE TABLE "+TABLE_ACCOUNTS+"(KEY_ID INTEGER PRIMARY KEY,KEY_TITLE TEXT,KEY_USERID TEXT,KEY_PASSWORD TEXT,KEY_LOGINURL TEXT,KEY_OTHERNOTES TEXT);";
It's possible if you made a mistake in creation query and then fix it,
So in the file system you have a db, but this db possibly has no such column.
Solution:
in emulator find a db file: data/data/com.somecompany.yourapp/databases/db and remove it, then try again.
It's also possible to open this file in some sql explorer and check if there is that column.
I ran into the same issue, as I updated my database table in sqlite with new columns during testing phase.
Besides the answers that were already given above, what I found really useful to update SQLite databases (e.g. after changes) is ABD Idea, an AndroidStudio plugin that allows you to:
Uninstall App
List item
Kill App
Start App
Restart App
Clear App Data
Clear App Data and Restart
You can just specify the version like this:
private static final int VERSION = 4;
If your sure your codes are OKAY, just try uninstalling the application, then rerun it agian. This solved my issue. Hope it helped
the possible solution also (not the best one) to use different version of DB, like:
public static final int DATABASE_VERSION = 2;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
it works for me.
clearing app data from the phone settings worked in my case.
either in the android emulator, you can do the same.
Current code is
override fun onCreate(db: SQLiteDatabase?) {
val createPWDTable =
"CREATE TABLE IF NOT EXISTS $tblPassword ($pwdId INTEGER PRIMARY KEY autoincrement,$title TEXT,$email TEXT,$pwd TEXT,$notes TEXT);"
db!!.execSQL(createPWDTable)
}
Now add colmn encrypted
override fun onCreate(db: SQLiteDatabase?) {
val createPWDTable =
"CREATE TABLE IF NOT EXISTS $tblPassword ($pwdId INTEGER PRIMARY KEY autoincrement,$title TEXT,$email TEXT,$pwd TEXT,$encrypted INT,$notes TEXT);"
db!!.execSQL(createPWDTable)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
if (newVersion == 2) {
val query = "ALTER TABLE $tblPassword ADD COLUMN $encrypted INT DEFAULT '0'"
db!!.execSQL(query)
}
}
Here if New user then oncreate method directly create table with encrypted value.
if Old user then onUpgrade method has check db version and alter the table
I know i have replie to this question to late but maybe someone can solve her problem with this answer.
You are put some data later in table database so the best solution is to re name your data base name.
In my case there was a query syntax error (need space b/w column name and datatype ..see attached image) in onCreate() method
to resolve it ..
I followed these steps
Correct your syntax error
change DB version number
Clear App data from settings
Uninstall and Run Your app again.]1]1
Hope it helps
Uninstall your app and reinstall your app and after that it will work fi
I have an android application that is supposed to read and expand a DataBase that is already created on SQLite...it works fine on emulator by putting database in data/data/(packagename)/database folder on the file explorer of emulator.
Now problem is occuring with the real device. Obviously it doesnt have the DataBase to open.I tried to put DataBase in assets folder but I am not getting to open it with the openhelper. how to access my database file form assets folder.will you please give me the right solution because i am new in Android and java .
this is my dbheperclass .
public class FoodDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "pkfood_calories.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE "+ Food.NewDishInfo.TABLE_NAME+"("
+ Food.NewDishInfo.DISH_NAME+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_QUANTITY+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_CALORIE+" INTEGER,"
+ Food.NewDishInfo.DISH_FAT+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_PROTEIN+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_SUGAR+" TEXT NOT NULL,"
+ Food.NewDishInfo.DISH_VITAMINS+" TEXT NOT NULL);";
public FoodDbHelper(Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
Log.e("DATABASE OPERATION","Database created / opened...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATION","Table created...");
}
public void addInformations(String name ,String quantity, Integer calorie, String fat ,
String protein,String sugar,String vitamins, SQLiteDatabase db){
ContentValues contentValues = new ContentValues();
contentValues.put(Food.NewDishInfo.DISH_NAME,name);
contentValues.put(Food.NewDishInfo.DISH_QUANTITY,quantity);
contentValues.put(Food.NewDishInfo.DISH_CALORIE,calorie);
contentValues.put(Food.NewDishInfo.DISH_FAT,fat);
contentValues.put(Food.NewDishInfo.DISH_PROTEIN,protein);
contentValues.put(Food.NewDishInfo.DISH_SUGAR,sugar);
contentValues.put(Food.NewDishInfo.DISH_VITAMINS,vitamins);
db.insert(Food.NewDishInfo.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATION","one row inserted...");
}
public Cursor getInformations(SQLiteDatabase db){
Cursor cursor;
String[] projections = {Food.NewDishInfo.DISH_NAME,Food.NewDishInfo.DISH_QUANTITY,
Food.NewDishInfo.DISH_CALORIE,Food.NewDishInfo.DISH_FAT,Food.NewDishInfo.DISH_PROTEIN,
Food.NewDishInfo.DISH_SUGAR, Food.NewDishInfo.DISH_VITAMINS};
cursor= db.query(Food.NewDishInfo.TABLE_NAME,projections,null,null,null,null,"DISH_NAME ASC");
return cursor;
}
please help me to short out from this problem..
First thing is your logic of reading from asset folder is correct.
But writing to assets folder may not be a better logic.
The asset folder is part of the APK
To read a file from asset folder
context.getAssets().open("pkfood_calories.DB")
Assuming that you placed that file in assets folder
You can get the internal memory location using
context.getFilesDir()
Refer creating file in internal memory Android create folders in Internal Memory
You cannot write anything to an APK. So, your db is in assert folder which can only be used for reading purpose.
You need to migrate that db file in external or internal memory(according to requirement) before doing some writing part on it.
I'm getting this error -
07-03 12:29:18.643: E/SQLiteLog(5181): (1) table accounts has no column named otherNotes
This is my code:
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "accountsManager";
private static final String TABLE_ACCOUNTS = "accounts";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_USERID = "userId";
private static final String KEY_PASSWORD = "password";
private static final String KEY_LOGINURL = "loginUrl";
private static final String KEY_OTHERNOTES = "otherNotes";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String CREATE_ACCOUNTS_TABLE = "CREATE TABLE " + TABLE_ACCOUNTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_USERID + " TEXT," + KEY_PASSWORD + " TEXT," + KEY_LOGINURL + " TEXT,"
+ KEY_OTHERNOTES + " TEXT" + ");";
db.execSQL(CREATE_ACCOUNTS_TABLE);
}
public void addAccount(AccountDetails account) {
SQLiteDatabase db = this.getWritableDatabase();
System.out.println("Hello!");
ContentValues values = new ContentValues();
values.put(KEY_TITLE, account.getTitle()); // Account Title
values.put(KEY_USERID, account.getUserId()); // account userid
values.put(KEY_PASSWORD, account.getPassword()); // account password
values.put(KEY_LOGINURL, account.getLoginUrl()); // account loginurl
values.put(KEY_OTHERNOTES, account.getOtherNotes()); // account othernotes
Log.v("title", KEY_TITLE);
// Inserting Row
db.insert(TABLE_ACCOUNTS, null, values);
db.close(); // Closing database connection
}
Also, when I remove the following statement:
values.put(KEY_OTHERNOTES, account.getOtherNotes()); // account othernotes
Then I get the same problem with password...etc.
i.e, (1) table accounts has no column named password
Please help!!
It seems that you added some columns later in the database. I do agree with Ken Wolf and you should consider uninstalling and re-installing your app. One better approach is, drop and recreate all tables in onUpdate method, and increase the db version every time you change the schema.
Well, If you are confindent about syntax for creating table, than it may happen
when you add new column in your same table, for that...
1) Unistall from your device and run it again.
OR
2) Setting -> app -> ClearData
OR
3) Change DATABASE_NAME in your "DatabaseHandler" class
( I faced same problem. But I suuceed by changing DATABASE_NAME.)
OR
4) Change DATABASE_VERSION in your "DatabaseHandler" class
(If you have added new column than it will upgrade autimatically)
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
As Benil says in a comment above, change the database version number and run the code again.
The SQL code looks fine.
I think that you forgot to call open() on your database object that you created.
add this methods to you SQL class:
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public DataBaseMain open() throws SQLException{
// Open the database to make her writeable, must be called before writing
// to database
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
// Closing the database for writing, avoids error.
ourHelper.close();
}
And use when you want to call you DB.
Try "Clear Data " of your App from Settings.
For me this problem was occuring because i was storage data on SD Card and later i added some columns.
So if you are saving on SD card delete the previous data.
For those who have similar problem and above solution is not worked then check 2 things:
Space between column name and data type like
COLUMN_NUMBER+" TEXT PRIMARY KEY) not COLUMN_NUMBER+"TEXT PRIMARY KEY)
The order of column during the creation of table should same as map for data insertion like
ContentValues values = new ContentValues();
values.put(TEST_ID, testId);
values.put(CLASS_NAME, className);
values.put(SUBJECT, subject);
"CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ TEST_ID + " INTEGER,"
+ CLASS_NAME + " TEXT,"
+ SUBJECT + " TEXT,"
Here It is your query..TRY this.
String CREATE_ACCOUNTS_TABLE = "CREATE TABLE "+TABLE_ACCOUNTS+"(KEY_ID INTEGER PRIMARY KEY,KEY_TITLE TEXT,KEY_USERID TEXT,KEY_PASSWORD TEXT,KEY_LOGINURL TEXT,KEY_OTHERNOTES TEXT);";
It's possible if you made a mistake in creation query and then fix it,
So in the file system you have a db, but this db possibly has no such column.
Solution:
in emulator find a db file: data/data/com.somecompany.yourapp/databases/db and remove it, then try again.
It's also possible to open this file in some sql explorer and check if there is that column.
I ran into the same issue, as I updated my database table in sqlite with new columns during testing phase.
Besides the answers that were already given above, what I found really useful to update SQLite databases (e.g. after changes) is ABD Idea, an AndroidStudio plugin that allows you to:
Uninstall App
List item
Kill App
Start App
Restart App
Clear App Data
Clear App Data and Restart
You can just specify the version like this:
private static final int VERSION = 4;
If your sure your codes are OKAY, just try uninstalling the application, then rerun it agian. This solved my issue. Hope it helped
the possible solution also (not the best one) to use different version of DB, like:
public static final int DATABASE_VERSION = 2;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
it works for me.
clearing app data from the phone settings worked in my case.
either in the android emulator, you can do the same.
Current code is
override fun onCreate(db: SQLiteDatabase?) {
val createPWDTable =
"CREATE TABLE IF NOT EXISTS $tblPassword ($pwdId INTEGER PRIMARY KEY autoincrement,$title TEXT,$email TEXT,$pwd TEXT,$notes TEXT);"
db!!.execSQL(createPWDTable)
}
Now add colmn encrypted
override fun onCreate(db: SQLiteDatabase?) {
val createPWDTable =
"CREATE TABLE IF NOT EXISTS $tblPassword ($pwdId INTEGER PRIMARY KEY autoincrement,$title TEXT,$email TEXT,$pwd TEXT,$encrypted INT,$notes TEXT);"
db!!.execSQL(createPWDTable)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
if (newVersion == 2) {
val query = "ALTER TABLE $tblPassword ADD COLUMN $encrypted INT DEFAULT '0'"
db!!.execSQL(query)
}
}
Here if New user then oncreate method directly create table with encrypted value.
if Old user then onUpgrade method has check db version and alter the table
I know i have replie to this question to late but maybe someone can solve her problem with this answer.
You are put some data later in table database so the best solution is to re name your data base name.
In my case there was a query syntax error (need space b/w column name and datatype ..see attached image) in onCreate() method
to resolve it ..
I followed these steps
Correct your syntax error
change DB version number
Clear App data from settings
Uninstall and Run Your app again.]1]1
Hope it helps
Uninstall your app and reinstall your app and after that it will work fi
Hello everyone,
I have built a sample app which takes input from user and save it in a table in a database.I have created my own database for my app and saved data in it. Every thing seems to be fine. The other day, I started Eclipse IDE and started running my application. I was not able to see any data in my application.
When I see in file explorer(DDMS), there was no database ( my database, table, data in it every thing lost). I heard that SQLite database is persistent. I used general syntax for creating database and table. Please any one suggest me why this has happened.
This is my MainActivity.java,
public class MainActivity extends Activity {
public final android.content.Context Context = MainActivity.this;
public String ReadingMode = "";
public String Value = "";
public String DialogStatus = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button saveWaterReadingToDB = (Button) findViewById(R.id.saveReading);
saveWaterReadingToDB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String TABLE_NAME = "WaterElectricity";
String COLUMN_NAME_READING_ID = "_Id";
String COLUMN_NAME_READING_MODE = "ReadingMode";
String COLUMN_NAME_PASTDATETIME = "StartDateTime";
String COLUMN_NAME_READINGVALUE = "ReadingValue";
final SQLiteDatabase DB = Context.openOrCreateDatabase(
"WaterElectricityReadingDataBase.db",
MODE_WORLD_READABLE, null);
final String CREATE_TABLE = "create table if not exists "
+ TABLE_NAME + " (" + COLUMN_NAME_READING_ID
+ " integer primary key autoincrement,"
+ COLUMN_NAME_READING_MODE + " text not null,"
+ COLUMN_NAME_PASTDATETIME + " date not null, "
+ "EndDateTime date not null, "
+ COLUMN_NAME_READINGVALUE + " integer not null" + ");";
DB.execSQL(CREATE_TABLE);
}
});
}
Thanks.
All databases may be deleted every time you restore/re-run your emulator.
Closing eclipse has nothing to do with your database deleting, as it's all saved in your emulators directory.
Your emulators database is actually stored on a piece of virtual memory. To see this (In windows) go to username/.android/avd and you will see all of your AVD's set up as directories (containing all files pertaining to that emulator)
Make sure this is unchecked:
File Path with Files:
SD Card img file (containing the actual db)?:
This is just me taking an educated guess on which file is the actual sdcard file. Someone feel free to correct me.
In my application I have a content provider which uses a database for the content provided. When the database is created the first time it needs to be filled from the raw content of a Json file. My idea was that i trigger this filling of the database at onCreate of my SQLiteOpenHelper subclass. This works fine yet I am not sure how to handle the the communication between application and content provider when the app is running the first time. Basically i would like to show some sort of a splash screen while the database is filled. Yet how does the application get informed that
the content provider is busy filling the database when running the first time
the content provider is ready to go
Surely I could fill the database from the application by calling the content provider with each dataset yet I would prefer doing it within the sphere of the content provider so that the application does not have to handle the reading of the json file etc. Besides design preferences it would also enable the content provider to fill the database more efficiently because it would have the whole dataset at once. I have a feeling this is not possible yet I hope I miss some simple point.
Any suggestions how to achieve this would be highly appreciated.
Thanks
martin
When using a content Provider i would presume that your using a DBHelper class to manage the creation of the database. Below is the code from the android notes example project.
This shows how the DBHelper constructor is intelligent enough to determine if the database has been created before. In the createDatabase method i would subsequently call a method to pre-populate the database, from as you say a json file.
The problem is that this doesn't really allow you to communicate to the Activity that your database hasn't been initialised.
One thought could be that you use SharedPreferences to store the fact you've populated the database. You could then check the sharedPreference in the activity on startup, Call the content provider to populate the database and then store in the shared preference that you've done this task already.
Just be aware that i'm not sure if the sharedPreferences maintain the same state as the database if you for example erase the data from the android settings menu. You'd need to check that.
http://code.google.com/p/android-notes/source/browse/trunk/src/com/bitsetters/android/notes/DBHelper.java?r=10
public class DBHelper {
private static final String DATABASE_NAME = "notes";
private static final String TABLE_DBVERSION = "dbversion";
private static final String TABLE_NOTES = "notes";
private static final int DATABASE_VERSION = 1;
private static String TAG = "DBHelper";
Context myCtx;
private static final String DBVERSION_CREATE =
"create table " + TABLE_DBVERSION + " ("
+ "version integer not null);";
private static final String NOTES_CREATE =
"create table " + TABLE_NOTES + " ("
+ "id integer primary key autoincrement, "
+ "note text, "
+ "lastedit text);";
private static final String NOTES_DROP =
"drop table " + TABLE_NOTES + ";";
private SQLiteDatabase db;
/**
*
* #param ctx
*/
public DBHelper(Context ctx) {
myCtx = ctx;
try {
db = myCtx.openOrCreateDatabase(DATABASE_NAME, 0,null);
// Check for the existence of the DBVERSION table
// If it doesn't exist than create the overall data,
// otherwise double check the version
Cursor c =
db.query("sqlite_master", new String[] { "name" },
"type='table' and name='"+TABLE_DBVERSION+"'", null, null, null, null);
int numRows = c.getCount();
if (numRows < 1) {
CreateDatabase(db);
} else {
int version=0;
Cursor vc = db.query(true, TABLE_DBVERSION, new String[] {"version"},
null, null, null, null, null,null);
if(vc.getCount() > 0) {
vc.moveToFirst();
version=vc.getInt(0);
}
vc.close();
if (version!=DATABASE_VERSION) {
Log.e(TAG,"database version mismatch");
}
}
c.close();
} catch (SQLException e) {
Log.d(TAG,"SQLite exception: " + e.getLocalizedMessage());
} finally {
db.close();
}
}
private void CreateDatabase(SQLiteDatabase db)
{
try {
db.execSQL(DBVERSION_CREATE);
ContentValues args = new ContentValues();
args.put("version", DATABASE_VERSION);
db.insert(TABLE_DBVERSION, null, args);
db.execSQL(NOTES_CREATE);
// Populate with data
populateDataBaseFromFile();// There are probably better ways to do this.
setSharedPreferenceYouPopulatedDB();
} catch (SQLException e) {
Log.d(TAG,"SQLite exception: " + e.getLocalizedMessage());
}
}
Personally I wouldn't bother with the splash screen, unless you really needed to.
Another thought might be to:
Write in the db helper a method to determin if your tables exist. Return false if not.
In startup activity call ContentProvider with a request that calls the DBHelper test method.
If false then display splash screen and then call Content Provider to populate DB.
If true, then carry on as normal.