Can I export my sqlite database from Flutter? - android

There are various articles on how to import data on the internal database from a csv, from another database etc .. but I haven't found anyone explaining how to export the flutter database.
The goal is to create a backup for each cell phone.
(So I need to understand where it is located for create a backup)

I assume you are using sqflite plugin for SQLite operations and path_provider for storage. The path of the database can be found using
String path = await getDatabasesPath(); // which is data/data/<package_name>/databases
Additionally, sqflite plugin doesn't provide any way to import/export database, here is an open issue, if you really want to do it, you will have to do it natively using MethodChannel, here is the solution for Android and AFAIK there is no way to do it in iOS.

if you use Sqlite to create database:
Step 1: When you create database, you set a directory for it, you can use path_provider like this:
var dir = await getApplicationDocumentsDirectory();
_dbPath = dir.path + '/$dbName';
so now you know what directory and path it is.
Step 2: Then use flutter_archive plugin to zip the file (This will zip the file in a directory, which is your db);
Step 3: use flutter_email_sender to send it by email, like this:
final email = Email(
body: 'content',
subject: 'content',
recipients: ['email'],
cc: ['email'],
attachmentPaths: [exportPath],
isHTML: false,
);
await FlutterEmailSender.send(email);
Your need to provide exportPath, which is the zip file path you set up.
It worked for us, hope this will help other people!

Usually on Android, databases are stored at
/data/data/your.app.signature.here/databases/.
But I don't know if that's different on flutter apps.
Hope that helps.

dependencies:
sqflite: ^2.0.0+3
path_provider: ^2.0.11
permission_handler: ^10.0.0
Export ( back up)
To export SQFLite database , I came across some errors , some of the error are
FileSystemException: Cannot open file, path
error: permission denied, errno = 13
etc........
I want to export my Database into Download folder that is ,
this is my Database path /data/user/0/com.example.reminder_app/databases/notes.db , it's a application directory path so my aim is to export notes.db file into this path
/storage/emulated/0/Download/
Expanding dBToCopy functions , this function will give path of Database
Future<File> dBToCopy() async {
final db = await instance.database;
final dbPath = await getDatabasesPath();
var afile = File(dbPath);
return afile;
}
full code bellow
dbExportToDownloadFolder() async {
File result = await NotesDatabase.instance.dBToCopy();
print("lllllllllllllllllll ${result.absolute.path}");
Directory documentsDirectory =
Directory("storage/emulated/0/Download/");
String newPath = join(documentsDirectory.absolute.path + 'abcde.db');
File b =
File("/data/user/0/com.example.reminder_app/databases/notes.db");
if ( await Permission.storage.request().isGranted &&
await Permission.accessMediaLocation.request().isGranted &&
await Permission.manageExternalStorage.request().isGranted )
{
File a = await b.copy(newPath);
} else {
print("No Permission Granted");
}
}
Note
File result = await NotesDatabase.instance.dBToCopy();
print("lllllllllllllllllll ${result.absolute.path}");
OutPut print
lllllllllllllllllll /data/user/0/com.example.reminder_app/databases
this result file not contain the notes.db file , only contain this path
/data/user/0/com.example.reminder_app/databases
To get the DatabaseFile
File b = File("/data/user/0/com.example.reminder_app/databases/notes.db");
or
File b = File("${result.path}"+"/notes.db");
so using the file b we can copy the file to Download folder file that is abcde.db
To do that create a file in Download , that is abcde.db
Directory documentsDirectory = Directory("storage/emulated/0/Download/");
String newPath = join(documentsDirectory.absolute.path + 'abcde.db');
and using the copy method , to copy one file to another file
File a = await b.copy(newPath);
Note
If you are getting permission denied errors and OS errors please add all permission in manifest , and using permission_handler allow all permissions
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION"/>
after the copying , A new file created in Download folder that is abcde.db

Related

how to creat a text file and write to it in android device by flutter(dart) [duplicate]

How do you read text from a file and write text to a file?
I've been learning about how to read and write text to and from a file. I found another question about reading from assets, but that is not the same. I will add my answer below from what I learned from the documentation.
Setup
Add the following plugin in pubspec.yaml:
dependencies:
path_provider: ^1.6.27
Update the version number to whatever is current.
And import it in your code.
import 'package:path_provider/path_provider.dart';
You also have to import dart:io to use the File class.
import 'dart:io';
Writing to a text file
_write(String text) async {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/my_file.txt');
await file.writeAsString(text);
}
Reading from a text file
Future<String> _read() async {
String text;
try {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/my_file.txt');
text = await file.readAsString();
} catch (e) {
print("Couldn't read file");
}
return text;
}
Notes
You can also get the path string with join(directory.path, 'my_file.txt') but you need to import 'package:path/path.dart'.
Flutter's Official Documentation of Reading and Writing Files
This works for iOS, Android, Linux and MacOS but not for web.
As additional info to #Suragch's answer, if you want to find the file you created, you can do as the images show:
And then inside that data folder, go again to a folder named data and search for your package, and then go to:
If you happen to create new files, in order to be able to see them, just right click and click Synchronize.
An another way to pull the file from the device is by using adb pull command. You can find the file path by debugging the code and then use adb pull command. adb is located in Android SDK -> platform-tools directory.
./adb pull /storage/emulated/0/Android/data/com.innovate.storage.storage_sample/files/sample.txt ~/Downloads
#Suragch 's answer is right. Except the version of path_provider that you want to use now is:
path_provider: ^2.0.9

Flutter: How to create a folder at the root of the directory, i.e, not under any directory

I am developing a file based application through flutter.
I can create a folder through getApplicationDocumentsDirectory() which gives the path to write files. But it cannot be seen in the files Explorer
I then created the folder through getExternalStorageDirectory() , which can be seen in the files explorer. But I want it to be created in the root.
You may have seen whatsapp folder in the root directory. I also want the same thing. I have tried the following:
Directory('FolderName').create()
But it gives the error saying 'read only os '
Is there a way to do it through flutter ?
You can do it this way:
String folderName = "My New Downloads";
var path = "storage/emulated/0/$folderName";
await new Directory(path).create();

Use Flutter 'file', what is the correct path to read txt file in the lib directory?

I am using the flutter 'file', trying to read a txt file in lib directory, but I do not know how should I write in code to read the file. I also do not know if I have placed the txt file at a right place, which means I do not know if I can read the file in the lib directory.
I have put a txt file words.txt in the lib directory, where other dart files are put.
Below is my code which tries to read the 'word.txt' file:
Future<String> readFile() async {
var text;
try {
final directory = await getApplicationDocumentsDirectory();
print(directory.path);
final file = File('${directory.path}/lib/words.txt');
text = await file.readAsString();
return text;
} catch (e) {
print(e.message);
}
}
P.S. I have imported the 'dart:io' and 'path_provider.dart'.
When I run the program, I can see the directory.path is printed in the console, however the e.message 'Cannot open file' is printed in the console.
I think that the error is came from 'File('${directory.path}/lib/words.txt')', so i would like to know how should i write code to read the txt file in lib directory.
Thanks.
Create an assets folder in your project's root folder. In Android Studio you can right click the Project outline and go to New > Directory.
So now you should have
root folder
--android
--ios
--lib
--assets
--build
Add your text file to the new folder
You can just copy your text file into the assets directory. The relative path of words.txt, for example, would be assets/words.txt.
Open the pubspec.yaml file that is in the root of your project.
Update it as
flutter:
assets:
- assets/words.txt
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
var s = await rootBundle.loadString('assets/my_text.txt');
print(s);//for debug
return s;
}

Nativescript: How to save a file in external storage (SD card)

After a lot of googling, and a lot of tries with "out-of-context" code, I'm begging you to help me.
I'm trying to figure out if it's possible to write on the external storage with Nativescript. I'm not interested to write within the application context. So what the docs shows, it's not what i'm looking for.
I've managed to achieve this from a thread on the Nativescript forum:
android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).toString();
It works, it gives me a path, but when I have this path I have no clue of what to do with it. How to create a file inside that path, read it etc.
What I need to achieve is to create a folder that both the user and the application can easily access. The user should be able to access this folder with the builtin files explorer.
The application runs on Angular.
I really struggled with this one on Android device and in the end it was due to:
Not making sure the required permissions has been granted by the user in the app
Using "Android File Transfer" on my Macbook to verify the files have been created and to download them
tns info
nativescript 6.0.3
tns-core-modules 6.0.7
tns-android 6.0.2
tns plugins
nativescript-permissions 1.3.7
example code
import * as fs from "tns-core-modules/file-system"
...
// First get the required permissions
// Note: this permissions should also be in your AndroidManifest.xml file as:
// <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
const permissions = require('nativescript-permissions')
permissions.requestPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
.then(() => {
console.log('Required Android permissions have been granted');
})
.catch(() => {
console.error('Required Android permissions have been denied!');
});
// Get the publicly accessable Downloads directory path
const sdDownloadPath = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).toString()
console.log('sdDownloadPath: ' + sdDownloadPath)
// Get a specific folder in that path (will be created if it does not exist)
const myAppFolder = fs.Folder.fromPath(fs.path.join(sdDownloadPath, 'myApp'))
console.log('myApp path: ' + myAppFolder.path)
// Get a file in that path (will be created if it does not exist)
// Note: In this case we try to get a unique file every time this code is run
let date = new Date()
date = date.toISOString().replace('.', '')
const myFile = myAppFolder.getFile(`myfile_${date}.txt`)
console.log('myFile path: ' + myFile.path)
// Write some data to this new file
myFile.writeText('Hello duder 123')
.then(() => {})
.catch((err) => console.log(`Error writing to file: ${err}`))
// Try and read back the data that was written
myFile.readText()
.then((res) => {
console.log(`Text read back: ${res}`)
}).catch((err) => {
console.log(err.stack);
});
// List all files in the myApp folder
myAppFolder.getEntities()
.then((entities) => {
// entities is array with the document's files and folders.
entities.forEach((entity) => {
console.log(entity)
});
}).catch((err) => {
console.log(err.stack);
});
android file transfer issue
One problem I wasted a lot of time on was that I could see the files with getEntities() but could not see them when using the 3rd party tool "Android File Transfer (AFT)" on Mac. I eventually stumbled across "Android Studio's -> Device File Explorer" and could see all my created files and folders with it so realised the issue is with AFT.
I now make use of Airdroid to browse and download device files.
applicable reference
https://docs.nativescript.org/angular/ng-framework-modules/file-system
(angular docs but relevant to nativescript-vue as well)
Do you know your external(sd card) path?
If it is like /storage/emulated/0, then you could try this to create a folder or file.
import * as fs from "tns-core-modules/file-system";
let externalPath= fs.path.join(android.os.Environment.getExternalStorageDirectory().getAbsolutePath().toString());
//Create a folder with known path
var folder: fs.Folder = fs.Folder.fromPath(sdCardPath+"/test");
//Create a file
var testFile: fs.File = folder.getFile("test.txt");
console.log("Path " + folder.path)
User should be able to access this fold and file. It is in device internal storage which is "external" folder.
I still try to figure out how to get access to sd card but hope above code work for you.
I have the same issue and finally solved it by adding android:requestLegacyExternalStorage="true" inside the AndroidManifest.xml file
follow the thread here

Unable to find the PCLstorage path in Android

I created a PCL project in Xamarin and I am trying to save files with a cross-platform solution using PCLstorage.
This is my code (from the example in PCLstorage website)
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder folder = await rootFolder.CreateFolderAsync("FolderName", CreationCollisionOption.OpenIfExists);
IFile file = await folder.CreateFileAsync("filename.txt", CreationCollisionOption.ReplaceExisting);
await file.WriteAllTextAsync("text");
Now, I want to know where this file is saved.
In Windows Phone, using WP power tools, I can explore the isolatedStorage of my app and I find and open the txt file. While, in Android, I can't find the folder created!
The path would be "data/data/com.appname.test/files/ but I don't find it!
Someone can help me?
You will be able to access to that folder only from the device (not from PC using USB cable) and only with root rights, so you need to root your device (try SuperSu from GooglePlay it work for most of the devices)
if you want to store it in external storage you can pass the folder path and create the file. so you can access that file physically.
string path="path";
IFolder rootFolder = await FileSystem.Current.GetFolderFromPathAsync(path);
IFolder folder = await rootFolder.CreateFolderAsync("folder", CreationCollisionOption.OpenIfExists);
IFile file = await folder.CreateFileAsync("file", CreationCollisionOption.ReplaceExisting);

Categories

Resources