ORMlite connect to an existing Sqlite Table Android - android

Is there a way to open a pre populated sqlite database using ORMLite. I am sure there is but then my next question is should I be using the following line of codes?
/**
* This is called when the database is first created. Usually you should call createTable statements here to create
* the tables that will store your data.
*/
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.i(DatabaseHelper.class.getName(), "onCreate");
TableUtils.createTable(connectionSource, Comment.class);
TableUtils.createTable(connectionSource , Words.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
}
Any help would be appreciated.

Is there a way to open a pre populated sqlite database using ORMLite.
To use existing databases, you will need to match your current schema precisely for it to work. You could also increase your database version and use the onUpgrade(...) method to tweak the database to have it match your ORMLite entities.
I am sure there is but then my next question is should I be using the following line of codes?
The onCreate(...) method is called to create new tables if they don't yet exist. To open up existing database (like your subject mentions), the onCreate(...) method will not be called.

Related

Updating preloaded sqlite database without losing user data in android

I have done a few searches and read a number of posts but I am still not successful trying to update a database without losing the data that is already saved.
I created the DB using this tutorial: http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
In the new database I want to migrate data from a main table to a new table that will store the user's favourites. Currently, they are stored in the main table. In the onupgrade function I tried renaming the table and inserting the record into the new table. That didn't work. I also tried saving the data to a cursor and then populating the new table but that didn't work. For these methods, I got errors saying that the new/old table cannot be found.
Below is the onUpgrade() function.
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE books rename to old_books");
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
db.execSQL("INSERT into favourites (_id, type, title, notes,rating) SELECT _id ,type, title, notes, rating FROM old_books where rating > 0;");
db.execSQL("DROP TABLE IF EXISTS old_books;");
}
}
Is there a better way to update the database without losing data using the implementation from the tutorial? All I need to do is copy the favourites from the "books" table and load them to the "favourites" table when users update the app.
onUpgrade is called while the database is open and a transaction is active.
You cannot overwrite the database file at this time (and this would lose all the data in the old file).
Just remove the copyDataBase() call.
if you are using SQLite browser to get preloaded database so you can update the database file then change it's version not create a new database file and keep the data ! Source tutorial .... in my opinion this tutorial is better and more detailed than the one you refereed.

android ORMLite populate table on database create

I'm using ORMLite in my android application. Is there a way when creating the database in the database helper to add some rows, or I must check in the main activity if there is already a database created and then create it and populate it if it doesn't exists.
What I want to achieve: When the application starts for the first time, add some data in the database (when creating the database file).
You can certainly add as much as you like in the onCreate or onUpgrade methods. Once you create the table, generate a DAO and do dao.create(...);.
If you look at the HelloAndroid example application, you can see that it does exactly that.
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
TableUtils.createTable(connectionSource, SimpleData.class);
// here we try inserting data in the on-create as a test
RuntimeExceptionDao<SimpleData, Integer> dao = getSimpleDataDao();
// create some entries in the onCreate
SimpleData simple = new SimpleData(System.currentTimeMillis());
dao.create(simple);
}

SQLite open helper to initialize a few entries

I'm new to programming. I'm making an Android app and I am at a new hurtle. I am using the SQLiteOpenHelper class to manage my database. Its been great, I am able to create tables, add entries and all that good stuff.
The problem I have is that for one of my tables I want to have an initial 7 entries that keep the same ID and can be replaced by the user. My plan is to use a SQLiteDatabase.replace() method in order to replace these entries. Since I want the entries to be set by me and then edited by the user, that means I want to add entries using the SQLiteOpenHelper class so that these entries are set only when the user installs the app and creates the database. I do not want to make a pre-populated database that I must include in the install package.
My Java skills are god awful so my main question is how do I add entries from inside my SQLiteOpenHelper class? I already know how to add entries in my other classes using the following method that I made:
public long createCategoriesSQLEntry(String name) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_CATEGORIES, name);
return myDatabase.insert(StringCategory_Table, null, cv);
}
Override the onCreate() in the database helper. Like this.
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try{
if(db.isOpen()){
//create tables here
db.execSQL("create table");
db.execSQL("insert row");
db.execSQL("insert row");
}
}
You are database will be installed when for the first time your application is installed. So, you write you data either in file and load it on onCreate method in SQLiteHandling class or just write the data in your java and call it in onCreated method like CyberTengu said.

Android onUpgrade() fails because database is locked, what should I do differently?

I have a project with a set of classes that are responsible for their respective database tables.
Each table managing class contains CRUD methods that follow the pattern of get connection, run crud operation, close connection:
public class PersonManager {
SQLiteDatabase db;
DbAdapter dbAdapter; //This is a subclass of SQLiteOpenHelper
public void addPerson(Person person)
{
ContentValues contentValues = new ContentValues();
contentValues.put("email", person.email);
contentValues.put("first_name", person.firstName);
db = dbAdapter.getWritableDatabase();
db.insert("person", null, contentValues);
db.close();
}
...other crud/utility methods omitted...
}
Now that I am upgrading my database via onUpgrade(), I run into database locked issues.
The exact error message follows:
CREATE TABLE android_metadata failed
Failed to setLocale() when constructing, closing the database
android.database.sqlite.SQLiteException: database is locked
It appears that onUpgrade is either meant to:
1 run db.execSQL() calls or
2 use helper classes that use onUpgrade()'s SQLiteDatabase rather than their own
It would be much easier to use my table managing classes to migrate data in onUpgrade() than db.execSQL() statements, or rewrite all my CRUD methods to take onUpgrade()'s SQLiteDatabase.
Am I setting up my database access correctly? If the above code follows the correct pattern, what should I do to fix this issue?
Thanks!
Here's your problem:
db = dbAdapter.getWritableDatabase();
When you're in onUpgrade(), you have to use the SQLiteDatabase handle that onUpgrade() provides you. So your solution is to rewrite your addPerson function to take one more argument -- an SQLiteDatabase handle:
public void addPerson(Person person, SQLiteDatabase db) {...}
If you need to call addPerson() from elsewhere in your project, then keep your current addPerson(Person person) function, have it do that
db = dbAdapter.getWritableDatabase()
call, and pass db to your two-argument version of addPerson().
I didn't get any answers, so I asked on a dev hangout.
According to the Android Developer Hangout Team, onUpgrade is only meant for structure alterations, not really for data migration/manipulation.

Android does not update SQLite database

I am experiencing some trouble with an SQLIte database in my Android application.
The issue is that the database is never updated, not even on multiple restarts of the emulator, of Eclipse or after deletion from DDMS.
This is my onCreate method, located in a class that extends SQLiteOpenHelper:
public void onCreate(SQLiteDatabase database) {
try {
database.execSQL(ESSENCE_TABLE_CREATE);
database.execSQL(PACCO_TABLE_CREATE);
database.execSQL(TAVOLE_TABLE_CREATE);
database.rawQuery("insert into essenza values(1, 'Rovere')",
null); // added later
} catch (SQLException e) {
Log.e("DB", e.getMessage());
}
}
After instantiating the helper, I request a reference to the database:
helper = new DBHelper(context, dbpath + "/" + DATABASE_NAME);
database = helper.getWritableDatabase();
It seems that the rawQuery statement (which was added at a later time) is not executed and that the database in use is instead cached from a previous version. I also tried to change the version of the database, but it did not work. Am I missing something? Thanks in advance.
You have two options:
Use DDMs to delete the database file from your device (look in /data/data/). This will force Android to run onCreate again.
In your constructor, increment the database version you pass to SQLiteOpenHelper. Add your raw query to onUpgrade.
You probably want option 1. Option 2 is better if you have users of your app whose databases you want to update.

Categories

Resources