Flutter fetch JSON from external Storage - json

I am trying to read a json file from external Storage (Android). But unable to do it.
I already setup the permission in manifest also checking the permission before reading. Though the file is already in the directory cannot read it.
ModelTestModel modelTestModel;
List<ModelTests> listModelTests;
Future<bool> get readPermission async {
await new Future.delayed(new Duration(seconds: 1));
bool checkResult = await SimplePermissions.checkPermission(
Permission.ReadExternalStorage);
if (!checkResult) {
var status = await SimplePermissions.requestPermission(
Permission.ReadExternalStorage);
if (status == PermissionStatus.authorized) {
var res = await fetchModelTest;
return res != null;
}
} else {
var res = await fetchModelTest;
return res != null;
}
return false;
}
Future<List<ModelTests>> get fetchModelTest async {
var dir = await getExternalStorageDirectory();
print(dir);
final data =
await rootBundle.loadString("${dir.path}/BCS/bsc.json");
print(data);
// var data = await rootBundle.loadString('assets/database/bcs-preparation.json'); this is working when when the file is inside assets
var jsonData = json.decode(data);
modelTestModel = ModelTestModel.fromJson(jsonData);
listModelTests = modelTestModel.modelTests;
return listModelTests;
}
Log
I/SimplePermission(17862): Checking permission :
android.permission.READ_EXTERNAL_STORAGE I/flutter (17862): Directory:
'/storage/emulated/0'
the permission is successful but cannot read the file

rootBundle is used to access the resources of the application, it cannot be used to access the files in phone storage.
Open the file with
File jsonFile = await File("${dir.path}/BCS/bsc.json");
Then decode this jsonFile using
var jsonData = json.decode(jsonFile.readAsStringSync());

Related

convert JSON to array -flutter

so im using sql_conn dependency on my flutter project to connect database to my flutter project.
im following the example in the flutter package site and using this method
var res = "";
Future<void> cetak(String query) async {
var req = await SqlConn.readData(query);
setState(() {
res = req;
});
}
the problem is, res is showing an Stringlike this
[{"CUST_NAME" : "MY NAME"}]
and i just want to show MY NAME later in Text() widget.
How do i parse res so i can get only MY NAME Value
try this, and read more here
import 'dart:convert';
var res = "";
Future<void> cetak(String query) async {
var req = await SqlConn.readData(query);
var parsedJson = jsonDecode(req);
setState(() {
res = parsedJson[0]['CUST_NAME'];
});
}
Try this once
var res = "";
Future<void> cetak(String query) async {
var req = await SqlConn.readData(query);
setState(() {
res =req[0]["CUST_NAME"];
});
}
Please try this let me know if it works for you if you need more modification then pls provide me with your print(req) so I can get more ideas and prepare as you want

How to read a json file without assets flutter

I'm trying to execute a json file that shows 2 routes with bat files.
To read the file I'm using a path_provider to localize the json file, so that part I have it already done. I need to know why the program can't reconize the text. I put all the information inside a list bc is the correct way to read all the information.
dynamic complete_route = '';
_functionX(String args1, String args2) async {
var shell = Shell();
try {
final dir = await getApplicationDocumentsDirectory();
String d = dir.path;
final path = d;
final route = await ('$path\\config.json');
String contenido = await _leerArchivo(route);
String local_route = complete_route;
shell.run('$local_route $args1 $args2');
} catch (e) {
debug('error', true);
debug(e, true);
}
}
List lista = [];
_leerArchivo(String ruta) async {
try {
//final File f = File(ruta);
final res = await json.decode(ruta);
lista = res["routes"];
complete_route = res.toString();
return lista;
} catch (e) {
return e.toString();
}
}
Add permission in menifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Put below permission in <application .... /application>
android:requestLegacyExternalStorage="true"
rootBundle is used to access the resources of the application, it cannot be used to access the files in phone storage.
Open the file with
File jsonFile = await File("${dir.path}/demofolder/demo.json");
Then decode this jsonFile using
var jsonData = json.decode(jsonFile.readAsStringSync());

Where is the default save location Flutter

when I write this code:
onSubmit(){
if(csvname.isEmpty){
print('type name');
}else {
File csvFile = new File(csvname + ".csv");
print('yesssss');
}
}
Does it even create a csv file?
If yes where is it saved or how can I view it?
Full Code / pastebin
It is not saving it with the code you posted, see this doc. Here is an example on how to write to a local file:
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath; return File('$path/counter.txt');
}
Future<File> writeCounter(int counter) async {
final file = await _localFile; // Write the file return file.writeAsString('$counter');
}

How to Store Object to windows phone 8.1

In wp8.0 we can store object to IsolatedStorageSettings. wp8.1 object was not storing. Is there any way to store object to wp8.1.
WRITE OBJECT CODE
NewsList = new ObservableCollection<New>(e.News);
var FileName = "News.xml";
DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection<New>));
var localFolder = ApplicationData.Current.LocalFolder;
var file = await localFolder.CreateFileAsync(FileName,CreationCollisionOption.ReplaceExisting);
IRandomAccessStream sessionRandomAccess = await file.OpenAsync(FileAccessMode.ReadWrite);
IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);
serializer.WriteObject(sessionOutputStream.AsStreamForWrite(), NewsList);
READ OBJECT CODE
var FileNameNews = "News.xml";
DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection<New>));
var localFolder = ApplicationData.Current.LocalFolder;
var newsFile = await localFolder.GetFileAsync(FileNameNews);
IInputStream sessionInputStream = await newsFile.OpenReadAsync();
newsVM = new NewsViewModel();
NewsVM.NewsList = (ObservableCollection<New>)serializer.ReadObject(sessionInputStream.AsStreamForRead());
im getting error on this link
IInputStream sessionInputStream = await newsFile.OpenReadAsync();
What mistake is there this code??
Thanks
This is how I do it. No using statements. I try to avoid the Stream syntax as much as possible.
Your error is very likely either because of concurrency (accessing the same file at the same time will throw an exception), or because the stream was not closed properly. I think it is the latter.
You do not dispose of your Stream objects properly (learn the using () {} syntax), which means that the stream remains OPEN after you're done writing. That means you hit the concurrency issue the second time you write, because you're trying to access a stream that's already open.
public async Task CreateOrUpdateData(string key, object o)
{
try
{
if (o != null)
{
var sessionFile = await _localFolder.CreateFileAsync(key, CreationCollisionOption.ReplaceExisting);
var outputString = JToken.FromObject(o).ToString();
await FileIO.WriteTextAsync(sessionFile, outputString);
}
}
catch (Exception e)
{
Debug.WriteLine("Encountered exception: {0}", e);
}
}
public async Task<T> GetDataOrDefault<T>(string key, T defaultValue)
{
try
{
T results = defaultValue;
var sessionFile = await _localFolder.CreateFileAsync(key, CreationCollisionOption.OpenIfExists);
var data = await FileIO.ReadTextAsync(sessionFile);
if (!String.IsNullOrWhiteSpace(data))
{
results = JToken.Parse(data).ToObject<T>();
}
return results;
}
catch (Exception e)
{
Debug.WriteLine("Encountered exception: {0}", e);
}
return defaultValue;
}

Node.js - Can I store writeable streams as JSON in Redis?

I am still working on fully understanding streams in node.js. If I create a writable stream, would I be able able to store the stream object as JSON in Redis, and then access it later, and continue writing to it (after JSON.parse)?
example:
var fs = require( 'fs' );
var redis = require( 'redis' );
var streamName = fs.createWriteStream(upfilePath, streamopts);
streamName = JSON.stringify(streamName);
rclient.set('streamJSON', streamName);
....
var myNewdata = 'whatever';
rclient.get('streamJSON', function (err, streamJSON) {
var recoveredStream = JSON.parse(streamJSON);
recoveredStream.write(myNewdata, function (err, written, buffer) {
//write successful??
}
}
You can't store variable references on redis. You would only need to store the filename, then reopen the stream with the a flag which allows you to append data to it.
I thought this was pretty an interesting question and created this that allows you to save the state of a stream and then use it later. But I don't see the point if you can just use the a flag. Might be useful for ReadableStreams though.
var fs = require('fs');
exports.stringify = function(stream) {
var obj = {
path: stream.path
, writable: stream.writable
, fd: stream.fd
, options: {
encoding: stream.encoding
, mode: stream.mode
}
};
if (stream.writable) {
obj.bytesWritten = stream.bytesWritten;
} else {
obj.options.bufferSize = stream.bufferSize;
obj.bytesRead = stream.bytesRead;
}
return JSON.stringify(obj);
};
exports.parse = function(json, callback) {
var obj = JSON.parse(json);
var stream;
if (obj.writable) {
obj.options.flags = 'a';
stream = fs.createWriteStream(obj.path, obj.options);
stream.bytesWritten = obj.bytesWritten;
} else {
stream = fs.createReadStream(obj.path, obj.options);
stream.bytesRead = obj.bytesRead;
}
// if stream was already opened, wait until it is
if (obj.fd !== null) {
stream.on('open', function() {
callback(null, stream);
});
} else {
process.nextTick(function() {
callback(null, stream);
});
}
return stream;
};