Il database della mia applicazione deve essere riempito con molti dati, quindi durante il onCreate()
, non sono solo alcune istruzioni di creazione tabella sql , ci sono molti inserti. La soluzione che ho scelto è di memorizzare tutte queste istruzioni in un file sql che si trova in res/raw e che viene caricato con Resources.openRawResource(id)
.Creazione di un'app per Android Database con una grande quantità di dati
Funziona bene, ma mi trovo di fronte al problema di codifica, ho accentuato i caratteri canel file sql che appare male nella mia applicazione. Questo mio codice per fare questo:
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);
}
La soluzione che ho trovato per evitare questo è quello di caricare le istruzioni SQL da un enorme static final String
invece di un file, e tutti i caratteri accentuati apparire bene.
Ma non c'è un modo più elegante per caricare le istruzioni sql di un grande attributo static final String
con tutte le istruzioni sql?
Grazie mille Dave – tbruyelle