I'm using Intent to export my .db file to the google drive. and import the .db file through the local folder on the device.
how can i import the file to my device from drive again?
what is the best way to "backup" the .db file and import the file?
it's possible to do that action without using "google drive api"?
Help me please !
public class BackUpDb {
Context context;
public BackUpDb(Context activity) {
this.context = activity;
}
public void exportDb(){
File direct = new File(Environment
.getExternalStorageDirectory()
+ "/folderToBeCreated");
if (!direct.exists()) {
if (direct.mkdir()) {
// directory is created;
}
}
try {
exportDB();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void importDb(){
importDB();
}
// importing database
#SuppressLint("SdCardPath")
private void importDB() {
try {
// File file = getBaseContext().getFileStreamPath(Environment.getExternalStorageDirectory()
// + "/MyDatabase");
// if(file.exists()){
FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory()
+ "/folderToBeCreated/MyDatabase");
String outFileName = "/data/data/com.example.application/databases/"+DbHandler.DB_NAME;
OutputStream output = new FileOutputStream(outFileName);
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();
Toast.makeText(context, "Ok :)",Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(context, "No list found",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#SuppressLint("SdCardPath")
private void exportDB() throws IOException {
// Open your local db as the input stream
try {
String inFileName = "/data/data/com.example.application/databases/"+DbHandler.DB_NAME;
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+ "/folderToBeCreated/MyDatabase";
// 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 (Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG)
.show();
}
Toast.makeText(context,
"save to :\n/folderToBeCreated",Toast.LENGTH_LONG).show();
}
public void sendDb(String mailAddres){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("application/octet-stream");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {mailAddres});
intent.putExtra(Intent.EXTRA_SUBJECT, "MyDatabase");
File root = Environment.getExternalStorageDirectory();
File file = new File(root, "/folderToBeCreated/MyDatabase");
if (!file.exists() || !file.canRead()) {
Toast.makeText(context, "No sd-card", Toast.LENGTH_SHORT).show();
return;
}
Uri uri = Uri.parse("file://" + file.getAbsolutePath());
intent.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(intent, "BACKUP"));
}
}
Since, Android 4.4 (KitKat), the ability to create files on external SD cards has been removed.
Related
I am trying to copy two files from assets folder to external storage, one is a text based and another one is a rar file(60 kb). But when i open the rar file in file manager, it says "wrong header". The size of the rar file which i get is 16kb.
private void copyAsset() {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(SKETCH_FILE);
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/Ardumation");
if (!dir.exists()) {
//System.out.println("creating directory: " + directoryName);
dir.mkdir();
}
//File outFile = new File(getExternalFilesDir(null), SKETCH_FILE);
File sketchFile = new File(dir, SKETCH_FILE);
File libraryFile = new File(dir, LIBRARY_FILE);
if (!sketchFile.exists()){
out = new FileOutputStream(sketchFile);
copyFile(in, out);
}
if (!libraryFile.exists()){
out = new FileOutputStream(libraryFile);
copyFile(in, out);
}
} catch(IOException e) {
Log.e(TAG, "Failed to copy asset file: ", e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
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);
}
}
Now what is wrong..?
Hello in my app i'm exporting the sharedPreferences file to my device storge and now, i want to import the file into the app again how can i do that ? here is the code for the export and what i tried to do for to import:
private void saveShared()
{
SharedPreferences prefs = context.getSharedPreferences(MySharedPreferences.MY_TEMP, 1);
File myPath = new File(Environment.getExternalStorageDirectory().toString());
File myFile = new File(myPath, MySharedPreferences.MY_TEMP.toString());
try
{
FileWriter fw = new FileWriter(myFile);
PrintWriter pw = new PrintWriter(fw);
Map<String,?> prefsMap = prefs.getAll();
for(Map.Entry<String,?> entry : prefsMap.entrySet())
{
pw.println(entry.getKey() + ": " + entry.getValue().toString());
}
pw.close();
fw.close();
Toast.makeText(context,
"Shared preferences saved!'",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
}
}
#SuppressLint("SdCardPath")
public void importSharedPreferences() {
try {
FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory().toString());
String outFileName = "/data/data/com.bibas.workclocks/databases/"+MySharedPreferences.MY_TEMP.toString();
OutputStream output = new FileOutputStream(outFileName);
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 (Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG)
.show();
}
}
Ive seen a few posts on how to import and export a database in android and i found these code, but i cant seem to make it work. I get the error java.io.filenotfoundexception /storage/sdcard0/BackupFolder/DatabaseName:open failed ENOENT (no such file or directory). Ive changed a few things but i still get no file found exception
here is my export:
private void exportDB() {
try {
db.open();
File newFile = new File("/sdcard/myexport");
InputStream input = new FileInputStream(
"/data/data/com.example.mycarfuel/data
bases/MyDatabase");
OutputStream output = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
db.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and my import:
private void importDB() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//" + "PackageName"
+ "//databases//" + "DatabaseName";
String backupDBPath = "/BackupFolder/DatabaseName
";
File backupDB = new File(data, currentDBPath);
File currentDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(),
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
}
SQlite database to our local file system-
Function declaration-
try {
backupDatabase();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Function defined-
public static void backupDatabase() throws IOException {
//Open your local db as the input stream
String inFileName = "/data/data/com.myapp.main/databases/MYDB";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/MYDB";
//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();
}
Above accepted answer will not work for Android version on or above 6 because database path is different.
please check below code . It will work on all devices.
public static boolean exportDB(Context context) {
String DATABASE_NAME = "my.db";
String databasePath = context.getDatabasePath(DATABASE_NAME).getPath();
String inFileName = databasePath;
try {
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory() + "/" + DATABASE_NAME;
OutputStream output = new FileOutputStream(outFileName);
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();
return true;
} catch (Exception e) {
return false;
}
}
I tried writing a file to my android phone using phonegap ui.
I have given the write permission and i tried by using getExternalStorageDirectory() and by giving the absolute path. But still not able to write it.
s1 is the name of the file that i am writing in the external storage
Environment.getExternalStorageState();
//File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"/Android/");
File file = new File("/mnt/sdcard"+ File.separator + "Android" + File.separator);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Folder");
}
}
Environment.getExternalStorageState();
File outputFile = new File(file, s1);
FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
byte abyte0[] = new byte[1024];
for (int i = 0; (i = inputstream.read(abyte0)) > 0;)
fileoutputstream.write(abyte0, 0, i);
fileoutputstream.close();
inputstream.close();
I wrote a quick working demo of writing a file to the external storage.
If this still doesn't work maybe it is a phonegap specific issue.
Hope this helps:
InputStream is = null;
OutputStream os = null;
byte[] buffer = new byte[2048];
int bytes_read = 0;
File inputFile = new File("/init.rc");
File outputFile = new File(Environment.getExternalStorageDirectory() + "/testfile");
try
{
is = new FileInputStream(inputFile);
os = new FileOutputStream(outputFile);
while ((bytes_read = is.read(buffer)) != -1)
{
os.write(buffer, 0, bytes_read);
}
}
catch (Exception ignore) {}
finally
{
try
{
is.close();
}
catch (Exception ignore) {}
try
{
os.close();
}
catch (Exception ignore) {}
}
if (outputFile.exists())
{
Toast.makeText(this, "Success!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "Failure!", Toast.LENGTH_LONG).show();
}
I'm desperately trying to copy a file to the sdcard from my raw folder, but it won't work! The file just doesn't show up in the file manager, and the program I give the path to (via an intent) can't find it either. This is what I'm trying...
private void CopyAssets() throws IOException {
String path = Environment.getExternalStorageDirectory() + "/jazz.pdf";
InputStream in = getResources().openRawResource(R.raw.jazz);
FileOutputStream out = new FileOutputStream(path);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
}
After which I try...
try {
CopyAssets();
} catch (IOException e1) {
e1.printStackTrace();
}
String aux = Environment.getExternalStorageDirectory() + "/jazz.pdf";
Uri path = Uri.parse(aux);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(bgn1.this, "No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
Just write out.flush(); in finally block and let me know what happen,
finally {
out.flush();
in.close();
out.close();
}
Update:
Working code:
private void CopyAssets() throws IOException
{
InputStream myInput = getResources().openRawResource(R.raw.jazz);
String outFileName = Environment.getExternalStorageDirectory() + "/jazz.pdf";
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();
}
}