Backup SQLite Database File to SD Card - android

So I have seen plenty of examples of backing up a SQLite database file to the SD card and I have gotten this to work successfully on the android emulator in development, however it does not work as expected on the phone itself. Here is the strange part that I do no understand. Backing up the file does actually create the file on the SD card, however not all of the data that is present in the SQLite database used by the application is contained in the file that is backed up. Has anybody else run into this issue? Below is the code I am using to backup the file. The DB_PATH constant contains the value of /data/data/[package name]/databases/. Any help with this would be greatly appreciated.
try
{
File dbFile = new File(DataBaseHelper.DB_PATH
+ DataBaseHelper.DB_NAME);
File exportDir = new File(Environment.getExternalStorageDirectory()
+ DB_BACKUP_PATH);
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
file.createNewFile();
FileUtil.copyFile(dbFile, file);
return true;
} catch (IOException e) {
BusinessLogic.errorHandler(e, ManageDataActivity.this);
return false;
}
catch(Exception e) {
BusinessLogic.errorHandler(e, ManageDataActivity.this);
return false;
}

You cannot access the database file without root privileges. That explains the behavior you're seeing.
Instead of copying the file itself, I would create a new database on the SD card and then try to copy all the data from the old database.

Related

Android: Cannot see file saved on external storage

public void write(View view)
{
String state;
File Dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if (!Dir.exists())
{
Dir.mkdir();
}
File file = new File(Dir,"nahk.txt");
Toast.makeText(getApplicationContext(),file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
String Message = "5nahk";
try {
FileOutputStream FOS = new FileOutputStream(file);
FOS.write(Message.getBytes());
FOS.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I have added write permission in the manifest xml file. This method is called when I press a button. The toast says that the txt file is saved in the Download folder of my Internal Storage (since I don't have an SD card in my LG G3). I open the file location (using FileManager on my LG G3) and there is no "nahk.txt" in that folder. Why can't I see the file?
I'm not familiar with native android development but I encountered something similar using cordova. After saving a file the file was not visible browsing with a usb cable but it was actually there. To see it had to restart my device.
So you could try to restart your device and check if it is still invisible (or create a method which fetches or checks the existence of the saved file to check if it is there).
edit: I learned this by googling so you should find it also
Try this
File Dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Your_Folder_Name";
File file = new File(Dir,"nahk.txt");
this file will save inside of your device storage Your_Folder_Name

Folder on phone not showing in Windows PC

I am writing an app to create a folder on my Nexus 5 and then write a text file inside the folder.
The above part is working just fine. I am writting using the following code:
Creating the folder:
File sdCard1 = Environment.getExternalStorageDirectory();
File dir = new File(sdCard1.getAbsolutePath() + "/SmsApp");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
File sdCard = Environment.getExternalStorageDirectory();
directory = new File (sdCard.getAbsolutePath() + "/SmsApp");
directory.mkdirs();
And writing the string to text file.
public void writeToText(String texttosave)
{
File sdCard = Environment.getExternalStorageDirectory();
File logFile = new File(sdCard.getAbsolutePath() + "/SmsApp" + "/smsrawdata.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(texttosave);
buf.newLine();
buf.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Text file is showing up properly on my phone but when I am trying to access the same folder on phone I can't see the folder at all.
I thought it would be the same for other app on play store that creates a folder but then everything gets created and then I can see them on Windows Explorer.
Am I doing something wrong in the code part for it not to show on my Computer but show only on my phone. I am using ES File Explorer to see files on my phone.
Please let me know if someone else is having the same problem.
Thanks!
Your pc will communicate with the media store about files. Not directly with the sdcard or external memory. If the media store does not know about your file your pc can not see it. You forgot to tell the store that you created a file. For every new file you should invoke the media scanner for that file. You are not the first one who happens this so the problem has been reported many times. You only need to add a few lines of code which you will find easily searching this site for invoking media scanner on new file. If you switch off/on your device the file will be known soon too.

Copy database when phone hasn't got external memory

I have got a problem with backup database in my app. I am working on Android 2.2.3 and this has sd card installed. Making copy of the database works fine. The problem occures when I'am testing my app on the phone with internal memory enought big like sd cards (Nexus 32gb). In this scenario my method doesn't work extracting file to sd card because it doesn't (sd card) exist. How to make copy of database to internal independed location? I've tried:
File outPut = new File(Environment.getRootDirectory().toString() + "/myfolder/");
but got permission denied and can not create folder with data. Can anyone show correct way?
EDITED:
I don't get it. I'd like to make new folder with dataBackup. I've defined correct location for that but it says that can not find file. SDCard is present. Why it can not create that folder - "/storeUGif/databaseName.db".?
Here is absolute path for destination folder:
public static final String OUTPUT_BACKUP_DATABASE = Environment.getExternalStorageDirectory().getAbsolutePath() + "/storeUGif/" + SqliteHelper.DATABASE_NAME;
if(isSdPresent())
{
//File outPut = new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/StoreUGif/"+SqliteHelper.DATABASE_NAME);
File outPut = new File(Tools.OUTPUT_BACKUP_DATABASE);
File storeUGif = new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString());
storeUGif.mkdir();
File currentDB = getApplicationContext().getDatabasePath(SqliteHelper.DATABASE_NAME);
FileInputStream is = new FileInputStream(currentDB);
OutputStream os = new FileOutputStream(outPut);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
}
else
{
Toast.makeText(this, "SDCard is unvailable", Toast.LENGTH_SHORT).show();
}
Use Environment.getExternalStorageDirectory() to get a valid path.
Despite its name, it will return the default storage, either the external or (if missiing) the internal one.
For reference: http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory()

Android: Possible to write into /etc folder?

I want to know whether it is possible to write data in /etc folder (or any other folder besides data)? If yes, how to do that?
And if not possible, any way to store a permanent data? For scenario example, an app is uninstalled (or clear data), but a specific file will still remain.
thank you.
i'm not sure about /etc folder, but the stuff saved in /data folder is managed by android automatically itself. So when you uninstall an app, anything related to it is also removed from data folder.
However, to store a file permanently besides Data folder on your SdCard, see the code below:
public static boolean saveOnFile(String msg){
boolean saved = false;
String filename = "yourFileName.extension";
try{
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File root = new File(Environment.getExternalStorageDirectory(), "/YourFolderOnSdCard/");
//create root folders if they do not exist
if(!root.exists()){
root.mkdirs();
}
//now lets save file in our directory structure
File file = new File(root, filename);
FileWriter fw = new FileWriter(file);
fw.append(msg);
fw.flush();
fw.close();
saved = true;
}
else
Log.e("Save", "Mounted media is not available or is write-protected");
}
catch (Exception e) { Log.e("Save", e.toString()); }
return saved;
}
This Data Storage guide could be useful.

To create a directory in Sd card inside an application

I want to create a directory on sd card keeping it as a separate activity in one of my application. I wrote the following code in the onCreate() of the application. It is not creating the directory though this code works fine if I try to implement it as an independent application.
Please suggest a solution for this problem.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
String dirName = "/sdcard/TEST";
File newFile = new File(dirName);
newFile.mkdirs();
Log.d("CaptureTest.java","Directory created");
if(newFile.exists()){
Log.d("capturetest.java","directory exists");
if(newFile.isDirectory()){
Log.d("capturetest.java","isDirectory = true");
}
else Log.d("capturetest.java","isDirectory = false");
} else
{
Log.d("capturetest.java","directory doesn't exist");
}
} catch(Exception e){
Log.d("capturetest.java","Exception creating folder " + e);
}
........................................
..........................................
}
The SD card might be mounted at /mnt/sdcard instead of /sdcard.
But the safest technique to get the external storage directory is like in the following code
File myDirectory = new File(Environment.getExternalStorageDirectory(), "my directory");
if(!myDirectory.exists()) {
myDirectory.mkdirs();
}
There could be a number of things causing this:
Check that external storage is available and writeable before trying to write to it.
Don't use String dirName = "/sdcard/TEST"; use Environment.getExternalStorageDirectory() or Context.getExternalFilesDir() instead.
This page has some really useful tips for correctly accessing the SD card.

Categories

Resources