I have an application in which I am updating my SQLite db file, but every time when the user uninstalls this application this db file is deleted and at reinstallation a new db file is created. I want to copy this db file after every update to a micro SD card so that after uninstallation I could be able to access my database.
Goal
Copy every time when db file is updated
say text.db when created
now I want to copy this db file to micro SD card
this db file (application db file) is being updated
now copy and replace this db file to micro sd card
Sudo code to copy the database to SD-Card. To copy it back, simply reverse the streams.
public boolean copyDatabase() {
String SDCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
// Create the directory if neccesary.
File directory = new File(SDCardPath + <PATH TO SD-CARD SAVE LOCATION>);
if (!directory.exists())
directory.mkdir();
// Close the database before trying to copy it
database.close();
// Copy database to SD-card
try {
InputStream mInput = new FileInputStream(<PATH TO DATABASE ON PHONE>);
OutputStream mOutput = new FileOutputStream(SDCardPath + <PATH TO SD-CARD SAVE LOCATION>);
byte[] buffer = new byte[1024];
int length;
while ((length = mInput.read(buffer)) > 0) {
mOutput.write(buffer, 0, length);
}
mOutput.flush();
mOutput.close();
mInput.close();
} catch (Exception e) {
}
return database.open();
}
Related
I have an android application that is supposed to read and expand a database that is already created on sqlite...it works fine on emulator by putting database in "data/data/(packagename)/database" folder on the file explorer of emulator. Now problem is occuring with the real device. Obviously it doesnt have the database to open.I tried to put database in assets folder but I am not getting to open it with the openhelper.
you should copy the .db file from your assets folder to an internal/external storage. You can use following codes,
private static String DB_PATH = "/data/data/your package/database/";
private static String DB_NAME ="final.db";// Database name
To create a database,
public void createDataBase() throws IOException
{
//If database not exists copy it from the assets
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist)
{
try
{
//Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
}
catch (IOException mIOException)
{
throw new Error("ErrorCopyingDataBase");
}
}
}
Check that the database exists here: /data/data/your package/database/DB Name
private boolean checkDataBase()
{
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
Copy the database from assets
private void copyDataBase() throws IOException
{
InputStream mInput = getApplicationContext().getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer))>0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
i hope it should help you.
you cant access the database from asset folder directly you need to copy it first to the path data/data/(packagename)/database then using it :
private String DB_PATH = "/data/data/" + "yourpackaename" + "/databases/" + "db.db";
in your onCreate()
is = getAssets().open("db.db");
write(is);
Then the method to call:
public void write(InputStream is) {
try {
OutputStream out = new FileOutputStream(new File(DB_PATH));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
is.close();
out.flush();
out.close();
System.err.println(out + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
You need to first copy the Database file from assests to application data location using java code.Can You Post some code to show How are you opening or handling the database?
You cannot directly open files from assets folder. Instead, you need to copy the contents of your assets folder on an internal/external storage and later use the File path to open the file.
In emulators, its easier for you to access the data folder of your apps. However, on a real non-rooted android device, its not possible due to security reasons.
Do you have a pre-populated database and looking to integrate into your app? If yes, you can simply do with my library
On your app's first launch after installation
SuperDatabase database=new SuperDatabase(getApplicationContext(),"foods.db", AssetDatabaseMode.COPY_TO_SYSTEM);
On subsequent launches
SuperDatabase database=new SuperDatabase(getApplicationContext(),"foods.db", AssetDatabaseMode.READ_FROM_DEVICE);
Simply fire SQL queries
database.sqlInject("INSERT INTO food VALUES('Banana','Vitamin A');");
Get results on Array in CSV, JSON, XML
ArrayList<String> rows=new ArrayList<String>();
rows=database.sqlEjectCSV("SELECT * FROM food;");
for (int i=0;i<rows.size();i++)
{
//Do stuffs with each row
}
You need to include my library for this. Documentations here:
https://github.com/sangeethnandakumar/TestTube
I wrote an app which logged data and saved it via SQL into a .db File. I had a method copying it from internal memory to SD card.
Now i wrote a second app, which needs to work with this particular .db file. As i think, that apps can't get access to package files from other apps
(in this case
/data/data/app1_package/databases/my_database.db
)
i need somehow to work with my DB on the SD Card. How do i do that?
Can i use this path in my SQLiteHelper class? Should i copy it from SD to my package, is that even possible (access rights etc.)?
I'm a beginner in databases, some help would be nice.
You can open any readable file path as a database:
File dbFile = new File( Environment.getExternalStorageDirectory(), "myfile.db" );
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile,null,null);
Note: check if sd-card is mounted before using this code.
yes place the DB file in your assets folder and get it this way :
DB_PATH="/data/data/app1_package/databases/my_database.db"
in your create :
is = getAssets().open("Meaniningss.db");
write(is);
the method :
public void write(InputStream is) {
try {
OutputStream out = new FileOutputStream(new File(DB_PATH));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
is.close();
out.flush();
out.close();
System.err.println(out + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
There are a few questions here on stackoverflow where people use BackupAgents to synchronize the apps data with googles cloud (see here). In my specific case the requirements are much more restrictive due to the nature of the more or less sensitive data. Everything must only be stored on the device itself and the app must not connect to the internet.
The main Activity contains a ViewPager which hosts a few ListFragments. Each ListFragment has its own Loader which swaps the cursor in a SimpleCursorAdapter class.
Before both backing up and restoring the database I destroy the loaders with:
getLoaderManager().destroy(LOADER_ID);
My backup function is similar to this anwser:
final String inFileName = "/data/data/<your.app.package>/databases/foo.db";
File dbFile = new File(inFileName);
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();
The restore function is similar in that it copies the database from the sdcard back into the internal app folder, stops the loaders and overwrites the database file.
public static void restore(Context context) throws IOException {
if (externalStorageIsWriteable()) {
// getBackupDir() is a path to the folder on the sdcard
File fileBackup = new File(getBackupDir(), WineSQLiteHelper.DB_NAME);
if (!fileBackup.exists()) {
throw new IOException("File not found");
}
File importFile = getImportDatabase();
try {
FileUtils.copyFile(fileBackup, importFile);
MySQLiteHelper dbHelper = new MySQLiteHelper(context);
dbHelper.close();
dbHelper = null;
File file = new File(Environment.getDataDirectory() + "/data/"
+ PACKAGE + "/databases/" + WineSQLiteHelper.DB_NAME);
FileUtils.copyFile(importFile, file);
// Remove temporary import file.
importFile.delete();
} catch (IOException e) {
throw e;
}
} else {
throw new IOException("External Storage not writeable");
}
}
But somehow the MainActivity gets recreated after I've overwritten the database file and I recieve a few
SQLiteException: no such column
My guess is that perhaps there are still open connections to the database, but I'm not sure about that since this is the first time I have to work with databases this closely.
How to properly close all database connections of a ContentProvider? I can't find anything in the documentation about this. And is this necessary?
How do I properly restore the database?
I have an SQLite database in my application. When I go to check if the database is created or not in File Explorer, there is no any database file within the data folder. It didn't even show up using the adb shell command. Does this mean that the database hasn't been created yet? Any suggestions on how to solve this?
If you are using an actual device, you will not be able to see or access it from outside unless you root your phone.
If you are using the emulator, the DDMS view will let you navigate to it and pull it from there.
Or, you could have an issue with creating your DB. Without seeing your code we cannot tell.
EDIT
If you want to get the file off of a real device, you'll need to implement a method to copy it from your data directory to someplace where you do have access (such as your SD card). This would do the trick:
public void backup() {
try {
File sdcard = Environment.getExternalStorageDirectory();
File outputFile = new File(sdcard,
"YourDB.bak");
if (!outputFile.exists())
outputFile.createNewFile();
File data = Environment.getDataDirectory();
File inputFile = new File(data, "data/your.package.name/databases/yourDB");
InputStream input = new FileInputStream(inputFile);
OutputStream output = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
throw new Error("Copying Failed");
}
}
I'm currently writing a phonebook-type application for the Android OS. I'm currently using a SQLiteDatabase to hold my contact information. I know that the database is held in
data/data/package-name/databases
However, I'd need root access to be able to find that directory on an Android phone. Is there a way to put the database somewhere I can find it without having to root the phone?
Just copy your DB to SD card programatically.
This code is an example how to access your DB =)
try {
input = new FileInputStream("/data/data/my_package_name/databases/" + DATABASE_NAME);
File dir = new File("/sdcard/database_dump");
dir.mkdir();
OutputStream output = new FileOutputStream("/sdcard/debugdump/myDb.db");
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer))>0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
After your DB is copied to the sd card you can take it and work with it on your PC using whatever SQLite editor you like. For example: http://www.softpedia.com/get/Internet/Servers/Database-Utils/SqlPro.shtml