My goal is to build a custom version of SQLite (specifically with R-Tree enabled) to include in my Android project. The motivation stems from:
Android SQLite R-Tree - How to install module?
SQLite has some instructions in how to do this:
http://www.sqlite.org/android/doc/trunk/www/index.wiki
I have compiled SQLite and successfully included the shared library in my project. The problem I am having is that as soon as I call an operation such as getReadableDatabase() or getWriteableDatabase() I receive a SQLiteCantOpenDatabaseException.
It is important to note that I am using:
import org.sqlite.database.sqlite.SQLiteDatabase;
import org.sqlite.database.sqlite.SQLiteOpenHelper;
in place of:
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
In order to use the custom SQLite build through the NDK and JNI.
MySQLiteHelper:
public class MySQLiteHelper extends SQLiteOpenHelper {
static {
System.loadLibrary("sqliteX");
}
private static final String DATABASE_NAME = "mydata.db";
private static final int DATABASE_VERSION = 1;
Context myContext;
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myContext = context;
}
public void getEntry(){
SQLiteDatabase db = this.getReadableDatabase();
db.close();
}
public void createEntry(){
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
//...
//...
db.close();
}
#Override
public void onCreate(SQLiteDatabase database) {
String create_rtree = "CREATE VIRTUAL TABLE demo_index USING rtree(\n" +
" id, -- Integer primary key\n" +
" minX, maxX, -- Minimum and maximum X coordinate\n" +
" minY, maxY -- Minimum and maximum Y coordinate\n" +
");";
database.execSQL(create_rtree);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + "demo_index");
onCreate(db);
}
}
Main Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MySQLiteHelper helper = new MySQLiteHelper(this);
helper.createEntry();
setContentView(R.layout.activity_my);
}
Stack Trace:
10-29 13:45:38.356 2360-2360/com.example.nathanielwendt.lstrtree E/SQLiteLog﹕ (14) os_unix.c:30589: (2) open(//arrrr.db) -
10-29 13:45:38.376 2360-2360/com.example.nathanielwendt.lstrtree E/SQLiteDatabase﹕ Failed to open database 'arrrr.db'.
org.sqlite.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at org.sqlite.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at org.sqlite.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:217)
at org.sqlite.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:201)
at org.sqlite.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:467)
at org.sqlite.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:189)
at org.sqlite.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:181)
at org.sqlite.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:809)
at org.sqlite.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:794)
at org.sqlite.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:699)
at org.sqlite.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:722)
at org.sqlite.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:228)
at org.sqlite.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:168)
at com.example.nathanielwendt.lstrtree.MySQLiteHelper.createEntry(MySQLiteHelper.java:65)
at com.example.nathanielwendt.lstrtree.MyActivity.onCreate(MyActivity.java:25)
I have seen several posts here on SO about this same exception, but they all seem to be related to importing the database from somewhere else on disk in which they do not set the file path correctly. This seems to be the most related post: Android SQLiteOpenHelper cannot open database file, but none of the suggestions worked.
I have tried this with 2 different phones and with the emulator and I receive the same error. Furthermore, I have replaced the imports discussed above with the default android sqlite imports and it works fine (given I don't try to create an R-Tree since it is not included in the default Android SQLite install). Changing permissions of database dir and .db file to 777 did not fix the issue, neither did adding WRITE_PERMISSION to my manifest.
This is an incompatibility in the SQLite Android bindings.
The original Android code opens the database like this:
db = mContext.openOrCreateDatabase(mName, mEnableWriteAheadLogging ?
Context.MODE_ENABLE_WRITE_AHEAD_LOGGING : 0,
mFactory, mErrorHandler);
while org.sqlite.database.sqlite.SQLiteOpenHelper does not use the context:
db = SQLiteDatabase.openOrCreateDatabase(
mName, mFactory, mErrorHandler
);
This means that the database path is not prepended to the database name.
Use something like this to get the complete path of the database:
String path = context.getDatabasePath(DATABASE_NAME).getPath();
and use that as the database name.
Related
I already have a database in my app using a 3rd party library. The library doesn't seem to have drop table functionality. So I was thinking to directly change it using SQLiteOpenHelper API. Is this possible?
I have created a class that extends SQLiteOpenHelper and give it the same db name as the one used in the library.
public class SqliteDatabaseHelper extends SQLiteOpenHelper {
// Database Info
private static final String DATABASE_NAME = "myDatabase";
private static final int DATABASE_VERSION = 1;
private Context context;
public SqliteDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
L.w("old: " + oldVersion + ", " + "new: " + newVersion);
if (oldVersion != newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + "deals_latest");
onCreate(db);
L.w("drop it like it's hot");
}
}
}
And I initialize it in Application class, just to see if it reflects the db class I created.
SQLiteDatabase db = new SqliteDatabaseHelper(this).getReadableDatabase();
L.w("version: " + db.getVersion());
L.w("path: " + db.getPath());
SqliteDatabaseHelper helper = new SqliteDatabaseHelper(this);
helper.onUpgrade(db, 1, 2); // this line suppose to invoke the drop table query
When running the app, onUpgrade() method doesn't seem to be called.
Mind you, I have never had any experience in using the native SQLite helper, so I have no idea what is going on here. My objective is just to see if the query in onUpgrade is executed or not. But the table still exists in the database.
How do I get around this?
The SQLiteOpenHelper class helps to manage versions of your own database.
It does not make sense to use it for a database that is managed by third-party code.
Just open the database directly with openDatabase().
I have uploaded an application to play store couple of weeks back. This application involves sqlite database that stores information on username, password, other details that given are by user while using the application locally.
Now I have couple of more tables and fields added to database and wanna upload the application to playstore as an update?
My worry is if the user updates the application from playstore - After update - all the data stored in database will be saved or will the user has to recreate everything from scratch?
Let me know!
Thanks!
You have to override the onUpgade method of SQLiteOpenHelper. In the OnUpgrade method you can either erase the data(drop sqlite command) or maintain the data with the additional columns(alter sqlite command) or create new table (create sqlite command).
Refer the following snippet.
I assume your version would be 1.(Plz check the constructor of your SqliteOpenHelper class)
Increment the version by 1.
class DatabaseHelper extends SqliteOplenHelper{
private static final int DATABASE_VERSION = 2; //new version of the database
private static final int Database_name = "MyDatabase";
private static final String alterUserName = "alter table users add name text";
private static final String table_users = "create table if not exists "
+ users + "(" + "_id integer primary key autoincrement,"
+ "email text" + ")";
public DatabaseHelper(Context context) {
super(context, Database_name, null, DATABASE_VERSION);
cntxt = context;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(table_users);
db.execSQL(alterUserName);
}
}
Now everytime when you roll the next update with database changes be sure to increment the database version by 1 else let it remain the same.
This isn't done for you automatically. In your SQLiteOpenHelper, you need to increment the Schema integer. This will trigger the on upgrade method for your existing users.
Adding a table is not a problem, just do this in onUpgrade, nothing breaks.
However to add fields, you should use the 'ALTER TABLE' SQL command
If you add new columns you can use ALTER TABLE to insert them into a live table. If you rename or remove columns you can use ALTER TABLE to rename the old table, then create the new table and then populate the new table with the contents of the old tab
See the official reference here
I'm running into a very frustrating bug.
I have a java class that reads in data from a file, and enters it into the database.
package edu.uci.ics.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbAdapter extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "mydb";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "fruits";
private static final String FRUIT_ID = "_id";
private static final String FRUIT_NAME = "name";
private static final String FILE_NAME = "fruits.txt";
private static final String CREATE_TABLE = "CREATE TABLE "+ TABLE_NAME + "("+FRUIT_ID+" integer primary key autoincrement, "+FRUIT_NAME+" text not null);";
private SQLiteDatabase mDb;
private Context mContext;
public DbAdapter(Context ctx){
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
mContext = ctx;
this.mDb = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
// populate database
try {
BufferedReader in = new BufferedReader(new InputStreamReader(mContext.getAssets().open(FILE_NAME)));
String line;
while((line=in.readLine())!=null) {
ContentValues values = new ContentValues();
values.put(FRUIT_NAME, line);
db.insert(TABLE_NAME, null, values);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public Cursor fetchAll() {
return mDb.query(TABLE_NAME, new String[] {FRUIT_NAME}, null, null, null, null, null);
}
}
EDIT:
To be more clear, this is what fails:
When I change the database name variable, the table name variable, the program force closes, indicating that something went wrong. Why can't I change the name of the table I create?
When I make changes in the fruits.txt file, I don't see anything reflecting those changes at run-time. Why does this happen?
SQLiteOpenHelper.onCreate() will only get called automatically if the database does not exist, which will only happen once. After that, the database file exists on the device's internal storage so it is simply going to load up the version it has.
If you want to create a new database when the external file is changed, you need to either delete the current database file (manual process) or also change the current database version the helper is created with. When Android sees that the version SQLiteOpenHelper is created with varies from the current file in internal storage, it will call onUpgrade() to allow the existing database to be modified to match the new "version".
EDIT:
To clarify, when you create a database, a db file is created (and persisted) on the device's internal storage, separate from your application's assets. When you re-run your application, persisted data storage does not clear out (or else it wouldn't be "persisted" anymore) so that database file from the last run of your application still exists...with all the settings from when it was created.
When you make changes to the variables in this class, it doesn't somehow magically modify the database file that already exists on the device, so now you are looking for tables and databases that don't exist (probably where your crashes are coming from).
If you simply need to clear out the database so it will reflect changes you've made during development, just clear the database manually on the device by going into Settings -> Manage Applications -> {Application Name} -> Clear Data. This deletes persisted files so they can be re-created by your application the next time you launch it.
If, however, you need this to somehow be a feature where your application automatically recognizes changes you've made to a file in /assets and modifies or re-creates the database as a result, then look at my previous suggestions about using the upgrade mechanism built into SQLiteOpenHelper
HTH
When you change the database name or table name in your code, they no longer reflect the names in the database on the device, so you get a force close. During development, the easy thing is to just uninstall your application and then reinstall whenever you make incompatible changes like that. When changing your database schema from one released version to another, you need to increase the database version number and do the right thing in onUpgrade().
For example, right now, you have
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
So when you change the table name in code from, say "fruits" to "veggies", onUpgrade() gets run, but table veggies doesn't exist, so it isn't dropped, and then you call onCreate(db) whith a conflicting shchema on top of the existing database. So you need to check oldVeresion and newVersion and do something more like
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion == 2 && oldVersion == 1) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME_V1);
db.execSQL("CREATE TABLE "+ TABLE_NAME ...);
}
}
If you're trying to change fruits.txt on the device, it won't work. That's how Android is designed: your assets never change, they're a read-only part of your APK. You need to write the fruit.txt file to the SD card if you want it to be able to change it.
I am getting following error while Version Creating My Database.
01-18 12:08:01.157: ERROR/AndroidRuntime(3079): Caused by: java.lang.IllegalArgumentException: Version must be >= 1, was 0
Please Help me regarding this.
Each database you create has a version number. That way you can keep track of them if you upgrade the application (perform necessary database changes for the upgrade on existing data). The version number must start from 1.
If you look at the following code:
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "
(id INTEGER PRIMARY KEY, name TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
onUpgrade will handle all necessary database upgrades. Sometimes you'll opt to just destroy (drop) the current database and create a new one.
it seems you have set previous version as 0, remove your app from phone, reinstall it, make sure new version is greater then previous one.
I have the following code (I simplified it & removed unrelevant parts)
public class MyDatabaseManager extends SQLiteOpenHelper {
private SQLiteDatabase myDatabase;
public DatabaseManager() {
super(MyApp.getAndroidContext(), DATABASE_NAME, null, DATABASE_VERSION);
myDatabase = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("create table t1 (t1key INTEGER PRIMARY KEY,data TEXT,num REAL,timeEnter NUMERIC);");
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
}
}
Now when I run queries against this database I get sqlite - no such table exception.
My breakpoint at database.execSQL hits and it doesn't raise any exception(for example if I change the code to database.execSQL("asda") I get syntax error exception) so I think my SQL code is correct. Yet the table is not created.
I copied the database file to my pc and I looked in it with Sqlite browser and indeed my tables don't exist there. There is only one table and that is something called android_metadata. Any ideas?
Sqlite doesn't have a datatype for DATE. I would suggest changing it to an INTEGER and storing date.getTime() in it.
Change your query and try something like:
create table t1 (_id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT,num REAL,timeEnter NUMERIC);
there should be a column _id in Android Sqlite Database table and better is it should be autoincrement.
Try passing the context when you instantiate the manager by changing the constructor as follows:
public MyDatabaseManager(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
public openDB() throws SQLException
{
myDatabase = getWritableDatabase;
}
Now pass getApplicationContext() to the new MyDatabaseManager instance in the activity's onCreate():
MyDatabaseManager manager = new MyDataBaseManager(getApplicationContext());
manager.openDB();
Ok, I fixed the problem. There were multiple problems:
1) My create table query had problems
2) I was programatically copying the database file to the sd card at the end of the onCreate and apparently there it was not yet written. I moved it right under myDatabase = getWritableDatabase();
and it worked.
Thanks all for triying to help.