Wednesday, 29 December 2010

Multiple SQL Tables Java Android?

How do you create multiple SQLite database tables in Java for an Android application?

I was having a really frustrating time of things when I was attempting to create multiple SQL tables for a single database for my Android App. It was a complete nightmare!

The Eclipse console kept on telling me that it could not find the table I had defined. I checked the code over and over again and all looked good so could not for the life of me figure out the problem!

Anyway it seems that the solution was to rename the database name in the code, before recompiling and starting again. Each time you make a change to your SQL database, you need to rename the database so a new version of it is created with the new settings. You do this by manually changing its name in the code, or by changing its version number.

Anyway, here is an example of how to create 2 SQL tables for a single SQL database in Java:

Define two SQL tables in the usual way:


public static final String DATABASE_CREATE= "create table " + DATABASE_TABLE + " (_id integer primary key autoincrement, col1 text not null);";

public static final String DATABASE_CREATE2= "create table " + DATABASE_TABLE_2+ " (_id integer primary key autoincrement, col1 text not null, col2 text not null, col3 text not null);";



Then you create each table seperately within the onCreate method of your SQL database adapter class:


public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
db.execSQL(DATABASE_CREATE2);
}


The error some people make is trying to do everything in one big string. Just to exactly the same as you did with your first table for other tables you add. Change the database name (or version) recompile, and all should be working nicely. Hopefully!

No comments:

Post a Comment