Database Copy From Assets

April 27, 2016 , 0 Comments

===== Use this Class to Copy to assets ===============================
public class DatabaseOpenHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "(databasename).sqlite";
private static final String DB_PATH_SUFFIX = "/databases/";
private static Context ctx;

public DatabaseOpenHelper(Context context) throws IOException {
super(context, DATABASE_NAME, null, 1);
this.ctx = context;
openDataBase();
}

public void CopyDataBaseFromAsset() throws IOException {

InputStream myInput = ctx.getAssets().open(DATABASE_NAME);

// Path to the just created empty db
String outFileName = getDatabasePath();

// if the path doesn't exist first, create it
File f = new File(ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX);
if (!f.exists())
f.mkdir();

// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);

// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}

// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();

}

private static String getDatabasePath() {
return ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX
+ DATABASE_NAME;
}

public SQLiteDatabase openDataBase() throws SQLException {
File dbFile = ctx.getDatabasePath(DATABASE_NAME);

if (!dbFile.exists()) {
try {
CopyDataBaseFromAsset();
System.out.println("Copying sucess from Assets folder");
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}

return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.CREATE_IF_NECESSARY);
}
}

======== How to Use DATABASE from Assets ===============================
try {
DatabaseOpenHelper dbHelper = new DatabaseOpenHelper(this);
} catch (IOException e) {
e.printStackTrace();
}

Contributer

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google

0 comments:

Popular Posts