Copy database from assets folder.
Keep database in your assets folder with predefine tables and with the help below class you can copy database into your app database folder from assets folder.
public class databasehelper extends SQLiteOpenHelper {
private static String DATABASE_NAME = "databasename.sqlite";
public static SQLiteDatabase myDataBase;
private Context myContext;
private String path = "/data/data/packagename/databases/";
private static CategoryWiseQandA item;
private static String DATABASE_NAME = "databasename.sqlite";
public static SQLiteDatabase myDataBase;
private Context myContext;
private String path = "/data/data/packagename/databases/";
private static CategoryWiseQandA item;
public databasehelper(Context context) {
super(context, DATABASE_NAME, null, 1);
this.myContext = context;
try {
createDataBase();
openDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
// ---Create the database---
public void createDataBase() throws IOException {
// ---Check whether database is already created or not---
boolean dbExist = checkDataBase();
if (!dbExist) {
this.getReadableDatabase();
try {
// ---If not created then copy the database---
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// --- Check whether database already created or not---
private boolean checkDataBase() {
try {
String myPath = path + DATABASE_NAME;
File f = new File(myPath);
if (f.exists())
return true;
else
return false;
} catch (SQLiteException e) {
e.printStackTrace();
return false;
}
}
// --- Copy the database to the output stream---
private void copyDataBase() throws IOException {
try {
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
String outFileName = path + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void openDataBase() throws SQLException {
// --- Open the database---
String myPath = path + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READWRITE);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
}
Comments
Post a Comment