I was previously storing a sqlite database in my apps assets folder but have now moved the database to external storage.
My previous copyDatabase() method looked like this.
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
OutputStream myOutput = new FileOutputStream(DB_PATH);
byte[] buffer = new byte[AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT];
while (true) {
int length = myInput.read(buffer);
if (length > 0) {
myOutput.write(buffer, 0, length);
} else {
myOutput.flush();
myOutput.close();
myInput.close();
return;
}
}
}
The issue is I'm unsure how to create an InputStream for opening the database from external storage. I can't seem to find the external storage equivalent to myContext.getAssets().open(DATABASE_NAME);
The current database path:
DB_PATH = Environment.getExternalStorageDirectory().getPath().toString()+"/SoulInfoDatabase/BB2SoulDatabase.db";
Step 1: Give storage permission in your App Manifesto file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step 2: Copy database to your custom SD card Path
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = context.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + "/" + DB_NAME;
// Open the empty db as the output stream
new File(outFileName).createNewFile();
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();
}
Step 3: Then Open your database:
try {
db = SQLiteDatabase.openDatabase(DB_PATH + "/" + DB_NAME, null,
SQLiteDatabase.OPEN_READWRITE
| SQLiteDatabase.NO_LOCALIZED_COLLATORS);
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
WHERE
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SoulInfoDatabase";
File file = new File(filePath);
if(!file.exists()){
file.mkdirs();
}
DB_PATH = filePath;
DB_NAME = "BB2SoulDatabase.sqlite";
Related
I've a HOSPITALS.db file in my assets folder. I want to access the data from the DB. I already have a code for accessing the data inside the table, I want to access the .db file itself so it won't produce an error not finding the table.
protected void openDatabase() {
db = openOrCreateDatabase("HOSPITALS", Context.MODE_PRIVATE, null);
}
Get Your Database path using the following
ContextWrapper cw =new ContextWrapper(getApplicationContext());
DB_PATH =cw.getFilesDir().getAbsolutePath()+ "/databases/"; //edited to databases
Then you can go this way
private void copyDataBase()
{
Log.i("Database",
"New database is being copied to device!");
byte[] buffer = new byte[1024];
OutputStream myOutput = null;
int length;
// Open your local db as the input stream
InputStream myInput = null;
try
{
myInput =myContext.getAssets().open(DB_NAME);
// transfer bytes from the inputfile to the
// outputfile
myOutput =new FileOutputStream(DB_PATH+ DB_NAME);
while((length = myInput.read(buffer)) > 0)
{
myOutput.write(buffer, 0, length);
}
myOutput.close();
myOutput.flush();
myInput.close();
Log.i("Database",
"New database has been copied to device!");
}
catch(IOException e)
{
e.printStackTrace();
}
}
My problem is that my application always fails when the database is copied from asset folder to the phone path:
/data/data/at.atn.android/databases/
MY databasename:
atnRoutenplaner.sqlite3
My code for the transfer:
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
File sampleFile = new File(outFileName);
//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();
}
try this,
public void CopyDataBaseFromAsset() throws IOException{
InputStream in = ctx.getAssets().open("mycontacts");
Log.e("sample", "Starting copying" );
String outputFileName = DATABASE_PATH+DATABASE_NAME;
File databaseFile = new File( "/data/data/com.copy.copydatabasefromasset/databases");
// check if databases folder exists, if not create one and its subfolders
if (!databaseFile.exists()){
databaseFile.mkdir();
}
OutputStream out = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer))>0){
out.write(buffer,0,length);
}
Log.e("sample", "Completed" );
out.flush();
out.close();
in.close();
}
Here is the code I am using (found in many answers):
InputStream myInput;
try {
myInput = iNezamApplication.getAppContext().getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_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 (IOException e1) {
e1.printStackTrace();
}
However, I always get an exception after reaching the OutpoutStream line:
java.io.FileNotFoundException: /data/data/package_name/databases/databasename.db: open failed: ENOENT (No such file or directory)
I tried something like this..
final String[] sample_dbName = {"DrugsNew.db"};
int assetDbSize = sample_dbName.length;
File databaseFile = new File( "/data/data/com.handyrep2.ui/databases");
// check if databases folder exists, if not create one and its subfolders
if (!databaseFile.exists()){
databaseFile.mkdir();
}
for(int i=0;i<assetDbSize;i++){
String outFilename =null;
outFilename = "/data/data/com.handyrep2.ui/databases"+ "/" + sample_dbName[i];
File sampleFile = new File(outFilename);
try {
InputStream in = activity.getAssets().open("offlinedb/"+sample_dbName[i]);
OutputStream out = new FileOutputStream(outFilename);
// Transfer bytes from the sample input file to the sample output file
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
// Close the streams
out.close();
in.close();
}catch(IOException e) {
}
}
Is "package_name" a substitute for your real package name just to post it here or do really use this in your DB_PATH? :)
you must create a File object at first
I want to use preexisting database file using ORMLite in android. I have database.db file of already creted database. I want to use it in my app.
My class extends OrmLiteSqliteOpenHelper.
Can any one have an idea? Please help
I use to copy database file into data path using
public static void copyDataBase(String path,Context c) throws IOException{
//Open your local db as the input stream
InputStream myInput = c.getAssets().open("Mydb.db");
// Path to the just created empty db
String outFileName = "/data/data/packageName/databases/databaseName";
String outFileName2 = "/data/data/packageName/databases/";
File file = new File(outFileName2);
if(!file.exists())
file.mkdirs();
//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();
}
But it wont help me .
This is kind of a stab in the dark since I do not know what your exact problem is, but can't you just specify the database file (and path) in the OrmLiteSqliteOpenHelper constructor?
OrmLiteSqliteOpenHelper(android.content.Context context, String databaseName, android.database.sqlite.SQLiteDatabase.CursorFactory factory, int databaseVersion)
Also there are a number of questions on this forum that deal with opening custom database files. This question is not ORMLite specific but they might get you forward since it open a custom database file.
Hope this help you a bit on your way.
I have solved the problem by below implementation
try {
String destPath = "/data/data/" + context.getPackageName()
+ "/databases";
Log.v("LOG", destPath);
File f = new File(destPath);
if (!f.exists()) {
f.mkdirs();
File outputFile = new File("/data/data/"
+ context.getPackageName() + "/databases",
"Name ofyour Database");
outputFile.createNewFile();
String DatabaseFile = "database file name from asset folder";
InputStream in = context.getAssets().open(DatabaseFile);
OutputStream out = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
Log.v("TAG", "ioexeption");
e.printStackTrace();
}
I used this tutorial to include a database file to my android app. It works fine on my HTC Decire HD. I wanted to run it on emulator to see if tablet layouts look well. Unfortunately the app fails with an error.
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//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){ <------ HERE, at first iteration
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
The message for this error is just 'null', nothing more. Can this be fixed?
private void copyfromAsset()
{
try {
String FILE_TO_READ="data.txt"; //file in asset folder
String TEMP_FILE_NAME="temp.txt"; //or whatever file name you want to give
byte[] buffer = new byte[1024];
int len1 = 0;
InputStream istr=(con.getAssets().open(FILE_TO_READ));
FileOutputStream fos=openFileOutput(TEMP_FILE_NAME,MODE_WORLD_READABLE);
while ((len1 = istr.read(buffer)) !=-1) {
fos.write(buffer, 0, len1); // Write In FileOutputStream.
}
fos.flush();
fos.close();
istr.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
try this method it is working fine for me....hit accept if you found usefull..
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
}
else {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are going to be able to overwrite that
// database with our database.
try {
copyDataBase();
}
catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transferring byte-stream.
*/
private void copyDataBase() throws IOException {
// Open your local DB as the input stream
InputStream myInput = mContext.getAssets().open(DB_NAME);
// Path to the just created empty DB
String outFileName = DB_PATH + DB_NAME;
// Open the empty DB as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the input-file to the output-file
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();
}