创建大量数据的Android应用数据库 [英] Creating android app Database with big amount of data
问题描述
我的应用程序的数据库需要填充大量的数据
所以在 onCreate()
,它不仅仅是一些创建表sql
指令,有很多插入。我选择的解决方案是
将所有这些说明存储在位于res / raw的sql文件中,并且
加载了 Resources.openRawResource(id)
。
The database of my application need to be filled with a lot of data,
so during onCreate()
, it's not only some create table sql
instructions, there is a lot of inserts. The solution I chose is to
store all this instructions in a sql file located in res/raw and which
is loaded with Resources.openRawResource(id)
.
它工作得很好,但我面对编码问题,我有一些突出的
caharacters在sql文件,这在我的应用程序中显得不好。这个
我的代码这样做:
It works well but I face to encoding issue, I have some accentuated caharacters in the sql file which appears bad in my application. This my code to do this:
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);
}
我发现避免这种情况的解决方案是加载sql指令
从一个巨大的 static final String
而不是一个文件,所有
加强字符出现得很好。
The solution I found to avoid this is to load the sql instructions
from a huge static final String
instead of a file, and all
accentuated characters appear well.
但是没有比所有sql指令大的
static final String
属性更加优雅的方式来加载sql指令吗?
But isn't there a more elegant way to load sql instructions than a big
static final String
attribute with all sql instructions?
推荐答案
我认为你的问题在这一行:
I think your problem is in this line:
return new String(buffer);
您正在将字节数组转换为 java.lang。 String
,但是你不是告诉Java / Android使用的编码。因此,由于使用了错误的编码,因此重音字符的字节未正确转换。
You're converting the array of bytes in to a java.lang.String
but you're not telling Java/Android the encoding to use. So the bytes for your accented characters aren't being converted correctly as the wrong encoding is being used.
如果使用 String(byte [], encoding>)
构造函数,您可以指定文件的编码,并且字符将被正确转换。
If you use the String(byte[],<encoding>)
constructor you can specify the encoding your file has and your characters will be converted correctly.
这篇关于创建大量数据的Android应用数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!