I am designing an application for an online exam. And I created a database using SQLite Browser and pulled it to Eclipse. In an emulator its working fine; it is able to retrieve and store data. But the problem comes when I place the .apk file on the mobile. On the mobile it's unable to retrieve the existing database. I am unable to bind the database file along with the .apk file, even after placing it in the assets folder.
Can anyone help?
Details:
Registration module
User Test module (display the questions from database)
Score submission module
How are you querying on database ?
The correct way is not to place a separate db in your code, but to create one dynamically. For e.g. the following code :
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSql("/*Put Create Table sqls here*/");
//onCreate will be called only once( when db doesn't exists for application, it creates here with the code)
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Use a database helper class like this in your code.
Now whenever you want to query on your db you can do it like this :
dbHelper = new DatabaseHelper(ctx);
db = dbHelper.getWritableDatabase();
//Start querying on db.(if it is not created oncreate() of dbhelper will create it for you.
So simply put your initial db create,/insert statements in oncreate() of dbhelper
Related
In my already created and deployed application, I've created a database MainDB, using a single class file which extended SQLiteOpenHelper, viz.
public class BaseSQLiteOpenHelper extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "MainDB";
....
....
}
Issue is I've tied this class, too much to a particular functionality.
Now I'm adding a totally new module in application, which will also interact with DB, but with different new tables.
Issue is I can't use the same class, as it is conflicting in more than one way. And even if I redesign the code, it will only add complexity from functional/understanding point of view.
So, I've decided to use same DB, but different tables.
Now I've already created DB in BaseSQLiteOpenHelper class.
So, how can I create new tables in seprate class using same DB?
One approach is to use separate Database as well, Or,
Create my new table in onCreate() in BaseSQLiteOpenHelper class only (issue with this is mentioning new table in same class seems awkward, as this class has nothing to do with my new table).
Please suggest.
Thank You
First check the current database version for this database
private final static String DATABASE_NAME = "MainDB";
private static final int DATABASE_VERSION = 1;
public BaseSQLiteOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
and increment the database version(DATABASE_VERSION), and add your new table query in on Upgrade and oncreate method like below.
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("old query no need to change");
db.execSQL("Create your new table here");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 2) {
db.execSQL("Create your new table here as well this for update the old DB");
}
}
Done!!!
Is it possible to delete any existing data set by a previous install of same app (databse tables and shared preferences etc) when the app is re-installed?
I have an app that stores some values in sqlite database, if the app is re-installed without prior properly uninstalling. I face problems from previous database entries etc.
If uninstalling the app didn't do the stuff try this :
System Parameters -> Manage Applications -> Your Application -> Clear data
If you click on the button (Clear data) you will see a dialog which shows you what kind of data will be cleared.
Edit:
If you want to do that programmatically, you can :
Change database version in the super method of the constructor:
super(context, DATABASE_NAME, null, NEW_DB_VERSION);
Add a drop statement before creating tables.
database.execSQL("DROP TABLE IF EXISTS your_table");
database.execSQL(" CREATE TABLE your_table ...");
Proceed to a hard drop of the database:
this.context.deleteDatabase(YOUR_DATABASE_NAME;
Its very Simple.
First Delete the table using drop query
sdb.execSQL("DROP TABLE IF EXISTS tablename");
and then again use the create table query
sdb.execSQL(" CREATE TABLE tablename(col1 TEXT PRIMARY KEY)");
or
delete the DB file using file explorer in path data->data->package->databases->dbname
update the Database version to greater value in the OpenHelper, it will automatically drop all the tables in database and recreate them.
For shared preferences.. you can clear them from the OpenHelper when onUpgrade is called.
Like Ankit Popli said, Using version is the right way to go:
public class Database extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "YourDBName.db";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// ALl the deletion operation here.
db.execSQL("DROP TABLE IF EXISTS "+Database.TABLE);
onCreate(db);
}
}
AndroidSqlite will automatically call onUpgrade function when the version number is incremented. Do all the database deletion there.
I have an app which consists of a common database accessed from native code and phonegap code of the same app, however, I am not able to access data written into the db by the native code in the phonegap code. I am using following code snippet for android -
public class DataBaseHandler extends SQLiteOpenHelper {
public DataBaseHandler(Context context) {
super(context, "dbName", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void addNotification(String data) {
SQLiteDatabase db = this.getWritableDatabase();
values.put("data", data);
db.insert("myTable", null, values);
db.close();
}
but when I try to accces the data from "myTable", I dont get any data and the table is empty, I have checked the ddms to ensure that data is populaated in the table, I am using the sqlite plugin for phonegap on android (https://github.com/pgsqlite/PG-SQLitePlugin-Android)
I have this doubt that could it be possible that native and phonegap parts are somehow using the different database and not the common database.
If you read code from https://github.com/litehelpers/Cordova-sqlite-legacy-build-support/tree/master/src/android/io/sqlc. The plugin code does not use SQLiteOpenHelper class to create sqlite database. The plugin is using another method SQLiteOpenFlags to create of database table. I have same problem like you also.
I have an app released on the android market which uses sqlite and displays data. I want to know if I am sending an update for the app by adding features, should I upload a new database? What happens when users already having my app, click on update? Will the database update on its own? If the users are downloading my app for the first time, they will certainly get the new db content...but what about the existing users?? I want to know if I have to explicitly update the database in the program
When you create your new version... If you change the version of the database... The onUpgrade function will run on all the existing users:
public static final int dbVersion = 2;
protected static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, dbName, null, dbVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
//create tables
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//what do you want to do to existing users? maybe recreate?
}
}
Why not create the sqlite database through code? That way your updates can update the SQL on the database (alter columns, add rows) without affecting the users existing data.
If you are changing database's attributes then on updation it will create problem and if the database's attributes are same then it will not have any effect...
You may use android.database.sqlite.SQLiteOpenHelper class it supports versions and migration mechanism
Hi I am new to android and I have a problem in creating a database.
public class database extends ListActivity {
/** Called when the activity is first created. */
private final String MY_DATABASE_NAME = "myCoolUserDB.db";
private final String MY_DATABASE_TABLE = "t_Users";
Context c;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> results = new ArrayList<String>();
setContentView(R.layout.main);
SQLiteDatabase mydb=null;
try
{
mydb.openOrCreateDatabase(MY_DATABASE_NAME, null);
} catch(Exception e){}
}
}
When I run this code it throws a run time exception. Please help me.
If you are going to call a static method like openOrCreateDatabase, do it on the class (SQLiteDatabase.openOrCreateDatabase(...)), not an instance. It's a lot clearer - the way you've done it looks like you're calling an instance method, so looks like a sure NullPointerException, which of course is misleading.
As someone else has stated, the stack trace would be the most useful thing when asking for help with an exception.
(Almost) never catch an exception without at the very least logging it. Don't just do nothing with it. There are of course exceptions to every rule, but let's not go there for the moment. Anyway, if you don't at least log it, you're just throwing away information that would tell you what went wrong when everything goes to crap later.
You shouldn't be using that method directly, and should instead be extending SQLiteOpenHelper . See the android developers page on data storage to get started (I'd post a link but apparently I'm only allowed one link in my post ?!), and since you've probably had to download the SDK to get going, look in the samples that come with it for the Notepad sample application. That contains a NotePadProvider class, which is a good example of both a content provider and database access, which often go hand-in-hand on android. I'd suggest compiling that application and making some simple changes to it before you jump into making your own one.
For working with sqlite database you need to create class extended from SQLiteOpenHelper:
private class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLES);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(UPGRADE_TABLES);
}
}
Then you can get access to db using DbHelper object:
DBHelper dbHelper = new DBHelper(Activity.this);
SQLiteDatabase db = dbHelper.getReadableDatabase();
I run into the same problem. It figures out that two bugs happens during development
dir "databases" was not existent
accendently ".db" was created as directory.
They following code cover both
File dbFile = getDatabasePath ("abc.db");
if (dbFile.isDirectory ()) {
dbFile.delete();
}
if (! dbFile.exists()) {
String path = dbFile.getParent ();
new File (path).mkdirs ();
}
database = SQLiteDatabase.openDatabase (dbFile.getAbsolutePath (), this, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY);
Hope this helps
I think SQLiteOpenHelper is only useful for "single table" databases. For multiple table applications I consider directly using SQLiteDatabase fit better to a good architecture.
This is a simple post which tells you how to insert data in to a SQLite database in Android and further more this links shows you how to retrieve data from a SQLite database in Android .