public

Copy sqlite database from assets dir - Android

  • Download Gist
AssetDatabaseOpenHelper.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
package com.javatarts.basketballgm.data;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
 
public class AssetDatabaseOpenHelper {
 
private static final String DB_NAME = "asset.db";
 
private Context context;
 
public AssetDatabaseOpenHelper(Context context) {
this.context = context;
}
 
public SQLiteDatabase openDatabase() {
File dbFile = context.getDatabasePath(DB_NAME);
 
if (!dbFile.exists()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
 
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
}
 
private void copyDatabase(File dbFile) throws IOException {
InputStream is = context.getAssets().open(DB_NAME);
OutputStream os = new FileOutputStream(dbFile);
 
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
 
os.flush();
os.close();
is.close();
}
 
}

Thanks! This was really useful.

Dude could you help me PLEASE. How can i read from the file? or how can i be sure that the db was created succesful on my device?

Thank you very much!

Doesn't work :(

How to call this from activity? any example?

AssetDatabaseOpenHelper adb = new AssetDatabaseOpenHelper(this);
SQLiteDatabase db = adb.openDatabase();
Cursor c = db.rawQuery("SELECT * FROM xxx;", null);
Log.d("MyApp", "cnt: "+c.getCount());

Te Felicito!! De maravilla tu aportaciĆ³n!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.