How to read preexisting database into Android using ORMLite - android

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();
}

Related

How to fetch already created .db and use it on Android Studio?

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();
}
}

Store db file in android app

I've implemented a parser that parses web-site and then i get a big object that consists of a lot of other objects and arrays and etc. What i want is i need to store all this data to SQLite database, then export the .db file.
Then i want to create an app which will work with that db file. How can i implement it in android?
can i store this db-file to assets and then replace the real db file of the app with this db-file that i get from assets?
Of course i can use json or xml or whatever, but it will take a lot of time to unwrap this data for the final user of the application.
So the idea is to generate the db-file once and then store in the assets.
So i've ended up with a solution. Here is a method to get the sqlite db file from your project
public void backupDB(){
// getDatabasePath
final String inFileName = "/data/data/com.example.yourproject/databases/books-db";
File dbFile = new File(inFileName);
try {
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/database_copy.db";
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0){
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
} catch (FileNotFoundException fileNotFoundException){
Log.e(LOG_TAG,"fileNotFoundException");
fileNotFoundException.printStackTrace();
}catch (IOException ioException){
Log.e(LOG_TAG,"ioException");
ioException.printStackTrace();
}
}
here is method to get it from assets to replace the db of other project, where you want to use this database instead of other.
private void copyAssets() {
AssetManager assetManager = mContext.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("database_copy.db");
String currentDBPath = "/data/data/com.example.somepackagename/databases/books-db";
out = new FileOutputStream(currentDBPath);
copyFile(in, out);
in.close();
out.flush();
out.close();
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file " , e);
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}

Opening a database from external storage Android

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";

Android - Copying Database from Assets

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

SQLiteException when copying/decompressing a zipped DB onto Android

Currently, I am copying a database from my assets folder to the to the /data/data/package folder. This is that code (from the answer here), which works:
public void copyDataBase() throws IOException{
// open db as input stream
InputStream myInput;
//open empty db as output stream
OutputStream myOutPut;
try {
myInput = myContext.getAssets().open(DB_NAME);
//path to newly created db
String outFileName =DB_PATH + DB_NAME;
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);
}
myOutPut.flush();
myOutPut.close();
myInput.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Now in order to save space in the .apk download, I am trying to zip the file before copying it to the /data/data/package folder.
private void copyDataBaseFromZipFile() {
InputStream inputStream = null;
OutputStream outputStream = null;
String sourcePathname = this.getBundledPathname();
String destinationPath = this.getDatabasePathname();
try {
inputStream = this.mContext.getAssets().open(sourcePathname);
ZipInputStream zipStream = new ZipInputStream(inputStream);
int BUFFER = 8096;
outputStream = new FileOutputStream(destinationPath);
BufferedOutputStream dest = new BufferedOutputStream(outputStream, BUFFER);
ZipEntry entry;
while ((entry = zipStream.getNextEntry()) != null) {
if (entry.getName().equals("androidDB.sql")) }
int count;
byte data[] = new byte[BUFFER];
while ((count = zipStream.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
}
}
outputStream.flush();
outputStream.close();
dest.flush();
dest.close();
zipStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
When I attempt to open the database later (with SQLiteDatabse), I get this error: android.database.sqlite.SQLiteException: unable to open database file
I haven't changed anything except the file I'm copy from, which is only a zipped version of the one I was previously copying over. The final database is the right size, so it doesn't seem to be still compressed... If anyone has any suggestions or possible reasons WHY it won't open, it would be greatly appreciated.
You should remove these lines:
outputStream.flush();
outputStream.close();
Your BufferedOutputStream probably has some buffered bytes, but since you close outputStream before you call dest.flush(), those bytes are never actually written to the file.

Categories

Resources