开发者

Problem when trying to iterate through a string array for execSQL

How do I do this: (why does it not work? - Emulator ends app without error message)

String [] aSQL;
aSQL = new String[50];

aSQL[0] = "CREATE TABLE tbl_team ("+
    "_id INTEGER PRIMARY KEY AUTOINCREMENT, "+
    "teamNa开发者_如何转开发me TEXT NOT NULL);";

aSQL[1] = "CREATE TABLE tbl_cardType ("+
    "_id INTEGER PRIMARY KEY AUTOINCREMENT, "+
    "cardTypeName TEXT NOT NULL);";

for (int i = 0; i < aSQL.length; i++){
    db.execSQL(aSQL[i]);
}

instead of having to do this:

db.execSQL(aSQL[0])
db.execSQL(aSQL[1])

If anybody wants to know why I am trying to do it this way. It is because I am on a tight schedule and don't know another way. I have tried and failed at making the database in SQLite browser. Putting it in assets folder and copying it over during install.

There are of course a lot more than 2 SQL commands to run.

Many thanks in advance for any help.


You can include a create_tables.sql file in assets, and then execute it on app start, like this:

InputStreamReader ir = new InputStreamReader(getAssets().open("create_tables.sql"));
BufferedReader br = new BufferedReader(ir);
SQLiteDatabase db = SQLiteDatabase.openDatabase(getDatabasePath("database.sqlite").getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE|SQLiteDatabase.CREATE_IF_NECESSARY);
String l;
while ((l = br.readLine()) != null) db.execSQL(l);

Update:

Okay so let's say you have

class MyApp extends Application {
  public static Application appContext;
  public void oncreate() { 
    appContext = this;

  }
}

And then anywhere you can do almost as above

BufferedReader br = new BufferedReader(new InputStreamReader(MyApp.appContext.getAssets().open("create_tables.sql")));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜