I want to use pre-loaded sqlite database which is as big as 250 Megabytes. I have copied the database into assets folder. Since we can not access the assets database directly, I am copying the database from assets into
"context.getFilesDir()" folder.
Using this strategy my app works well for small database up to 5-6 megabytes but app crashes if I do so for large database, which is what I want.
Is there any better way or something wrong with what I am trying to do? I have already tried solutions of the possible copies Android: Accessing assets folder sqlite database file with .sqlite extension Getting a column from .sqlite containing multiple tables with multiple columns How to use preloaded SQLite database in Android from Assets
My code for SqliteHelper is given below for reference.
package com.example.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
/**
* Created by MOHIT on 06-08-2014.
*/
public class SQLiteHelper {
private static final String DB_NAME = "alldb.sqlite";
//private String DB_NAME = "alldb.sqlite";
private Context context;
private SQLiteDatabase database;
public SQLiteHelper(Context context) {
this.context = context;
}
public SQLiteDatabase openDatabase() {
File dbFile = new File(context.getFilesDir(), DB_NAME);
if (!dbFile.exists()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
// Utilities.makeToastLong(context, "Error here");
throw new RuntimeException("Error creating source database", e);
}
}
database= SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
return database;
}
public void closeDatabase()
{
if(database!=null&& database.isOpen())
database.close();
}
private void copyDatabase(File dbFile) throws IOException {
try {
InputStream is = context.getAssets().open(DB_NAME);
dbFile.createNewFile();
OutputStream os = new FileOutputStream(dbFile,false);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
}catch (Exception e)
{
Log.e(SQLiteHelper.class.getSimpleName()," Error in Database copy "+e.getLocalizedMessage());
}
}
}