My application database should be filled with a lot of data, so during onCreate() it not only creates a table of sql instructions, there are many inserts. The solution I chose is to save all of these instructions in a sql file located in res / raw and which is loaded using Resources.openRawResource(id) .
This works well, but I am facing a coding problem, I have some accented caharacters in the sql file, which seems bad in my application. This is my code for 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); }
The solution I found to avoid this is to load sql statements from a huge static final String instead of a file, and all accented characters display well.
But is there a more elegant way to load SQL commands than a large static final String with all sql statements?
java android database
tbruyelle
source share