Sunday, April 10, 2011

Using a Preexisting Database with the Android OS

Having just completed a project where I had to implement a preexisting SQLite database on the Android, I figured I'd put this post together to help others who may be having trouble getting it to work.

Most Android developers want to create a new database at run time, and not use something made beforehand. My particular project was to take a database of bus arrival times for certain stops around my city and upload it onto the phone as the application was installed, allowing users to find their desired bus times.

I ran into several problems in trying to do this. First of all, if your database isn't formatted in such a way that Android cannot read it, then your database simply will not work. Below is a compiled list of every tip and trick I was able to figure out, and find elsewhere on the internet:



This is an example of a database I was trying to convert into an Android supported format. As you can see, there are indexes to this database, in addition to several primary key types, with varying names.

In order to convert your database to an Android supported format, download SQLite Database Browser (available from sourceforge) and follow the instructions in this post.

Now you should have a database formatted to look something like this:



Assuming you've done that, I will point out that there cannot be indexes in your database. In addition to this, all of your primary keys need to be of the type INTEGER PRIMARY KEY. Any other SQLite format will not work on the Android. Secondly, as mentioned in the above post, all primary key names need to be "_id".

You can skip the part where you insert the Android meta data into your database if you set the NO_LOCALIZED_COLLATORS flag when opening your database. Example:

db = SQLiteDatabase.openDatabase(fileName, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS |
SQLiteDatabase.CREATE_IF_NECESSARY);

Now that your database is set up, a few more things need to be mentioned. If your database is over 1 Mb in size, the Android OS will try to compress the file upon being uploaded to the phone. So assuming you are using an SQLite database with a .db extension, it will be compressed. However, if you rename your database to a format that won't be compressed by the Android OS, your database will upload correctly. So try renaming it to database.mp3 for example, and you should be good to go.

That is basically all the tips I have that weren't discussed in other blog posts. If you have any questions let me know in the comments section below.

Labels: , , , , , , , , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home