我的应用程序数据库需要填充大量数据,所以在onCreate()
期间,这不仅仅是一些创建表sql 的说明,还有很多插入。我选择的解决方案是 将所有这些指令存储在位于res/raw的sql文件中,并且其中 加载了Resources.openRawResource(id)
。创建android应用程序数据库数据量大
它运行良好,但我面对的编码问题,我有一些强调 字符在SQL文件中出现在我的应用程序不好。这 我的代码来做到这一点:
public String getFileContent(Resources resources, int rawId) throws
IOException
{
InputStream is = resources.openRawResource(rawId);
int size = is.available();
// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// Convert the buffer into a string.
return new String(buffer);
}
public void onCreate(SQLiteDatabase db) {
try {
// get file content
String sqlCode = getFileContent(mCtx.getResources(), R.raw.db_create);
// execute code
for (String sqlStatements : sqlCode.split(";"))
{
db.execSQL(sqlStatements);
}
Log.v("Creating database done.");
} catch (IOException e) {
// Should never happen!
Log.e("Error reading sql file " + e.getMessage(), e);
throw new RuntimeException(e);
} catch (SQLException e) {
Log.e("Error executing sql code " + e.getMessage(), e);
throw new RuntimeException(e);
}
我发现避免这个问题的解决方案是从一个巨大的static final String
而不是文件加载SQL指令 ,所有 强调字符显示良好。
但是,是不是有一个更优雅的方式来加载SQL指令比所有SQL指令的大 static final String
属性?
非常感谢Dave – tbruyelle 2009-12-23 16:56:04