用大量数据创建android app数据库

tbr*_*lle 6 java database android

我的应用程序的数据库需要填充大量数据,所以在onCreate()这期间,它不仅是一些create table sql指令,还有很多插入.我选择的解决方案是将所有这些指令存储在res/raw中的sql文件中并加载Resources.openRawResource(id).

它运作良好,但我面对编码问题,我在sql文件中有一些突出的caharacters,在我的应用程序中看起来很糟糕.这是我的代码:

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);
        }
Run Code Online (Sandbox Code Playgroud)

我发现避免这种情况的解决方案是从一个巨大的static final String而不是一个文件中加载sql指令,并且所有突出的字符都显示得很好.

但是加载sql指令的方法是否比static final String使用所有sql指令的大属性更优雅 ?

Dav*_*ebb 8

我认为你的问题在于这一行:

return new String(buffer);
Run Code Online (Sandbox Code Playgroud)

您正在将字节数组转换为a,java.lang.String但您不会告诉Java/Android使用的编码.因此,正在使用错误的编码时,重音字符的字节未正确转换.

如果使用String(byte[],<encoding>)构造函数,则可以指定文件的编码,并正确转换字符.