How to make my flutter app read upadated json file instead of old json file? - json

I made a app where I have to first read local json file and updated some content of it inside app and save that file and without closing the app I want to display the changes by reading updated json file.
I am able to read my json file, save changes in that file but when I try to see my changes without closing the app by reading that json file, it always show my previous data. But if I close my app and open it again It show read new updated file.
How can I show changes by reading updated json file without closing the app??
This is my code:
First I read json file inside initstate:
Future<void> readJson() async {
final String response =
await rootBundle.loadString('jsonfile/primary_values.json');
final data = jsonDecode(response);
var values = PrimaryValueJson.fromJson(data);
setState(() {
if (primaryKey == 'Doctor SSN :') {
widget.primaryIndex = values.doc_ssn;
widget.primaryValue = 'DC0${widget.primaryIndex}';
print(widget.primaryValue);
print('this is readjson');
}
});
}
#override
void initState() {
super.initState();
print("I am doctor init screen");
readJson();
}
And then I increment Doc.ssn by 1 and write it by clicking a button. Function associated with that button is:
_writeJson() async {
print("this is 1st line writejson: ${widget.primaryIndex}");
String response =
await rootBundle.loadString('jsonfile/primary_values.json');
File path = File('jsonfile/primary_values.json');
var data = jsonDecode(response);
var values = PrimaryValueJson.fromJson(data);
final PrimaryValueJson doctor = PrimaryValueJson(
doc_ssn: values.doc_ssn + 1,
phar_id: values.phar_id,
ssn: values.ssn,
);
final update = doctor.toJson();
path.writeAsStringSync(json.encode(update));
print('this is writejson:${doctor.doc_ssn}');
nameController.text = '';
specialityController.text = '';
experienceController.text = '';
widget.primaryIndex = doctor.doc_ssn;
widget.primaryValue = 'DC0${doctor.doc_ssn}';
}
Future<void> insertRecord(context) async {
count = count + 1;
if (nameController.text == '' ||
specialityController.text == '' ||
experienceController.text == '') {
print("Please fill all fields");
} else {
try {
String uri = "http://localhost/hospital_MS_api/insert_doctor.php";
var res = await http.post(Uri.parse(uri), body: {
"Doc_SSN": widget.primaryValue,
"name": nameController.text,
"speciality": specialityController.text,
"experience": experienceController.text,
});
setState(() {
_writeJson();
});
var response = jsonDecode(res.body);
if (response["success"] == "true") {
print("Record Inserted");
} else {
print("Record not inserted");
}
} catch (e) {
print(e);
}
}
}

Assets are read-only. After writing an asset file to a file, read also from that file.
File path = File('jsonfile/primary_values.json');
...
path.writeAsStringSync(json.encode(update));
...
var data = jsonDecode(path.readAsBytesSync());

Related

How to retrieve entire Logger output?

I have large sets of data (mainly arrays and objects with many elements) and I am trying to log out the entire result to check for bugs. However, in some cases it says "Logging output too large. Truncating output." Where can I see the output in its entirety? I am working with Map Objects and trying to debug why my calculations don't match Google's output.
Logger.log is limited to the number of lines that it can contain. However you can make your own logger and save it to a text file.
var Log = null;
function testLogger() {
try {
Log = new LogFile("testLogFile");
test1();
test2();
throw "done"
}
catch(err) {
Log.log(err);
Log.save();
}
}
function test1() {
Log.log("in test1");
}
function test2() {
Log.log("in test2");
}
class LogFile {
constructor (name) {
if( name === undefined ) name = "_LogFile"
this.name = name;
this.text = [];
}
log(text) {
this.text.push(text);
}
save() {
try {
let text = "";
this.text.forEach( line => text = text.concat(line,"\n") );
let files = DriveApp.getFilesByName(this.name);
let file = null;
if( files.hasNext() ) {
file = files.next();
file.setContent(text);
}
else {
DriveApp.createFile(this.name,text);
}
}
catch(err) {
Logger.log(err);
}
}
}
The text file is shown below.

Get all json data from web in flutter

Hello I am trying to get all json data from this page:
https://www.espn.com/soccer/team/_/id/4438&xhr=1
But in response.body only contains part off json
I get data here:
Future<NextPartido> getPartidoHome() async {
var response = await http.get(baseUrl);
if (response.statusCode == 200) {
var body = json.decode(response.body);
print(body);
// JsonEncoder encoder = new JsonEncoder.withIndent(' ');
// String prettyprint = encoder.convert(body);
// log('movieTitle: $prettyprint');
//
return NextPartido.fromJson(body);
} else {
return throw Exception('Error getting partidohome');
}
}
I have model class generate here:
https://app.quicktype.io/
Is posible that response.body not contains all json data??
And how I can get all json in response?
If you want to have all data your model should be like this :
=> https:// paste.of code.org / Vt6YciMmTLkirmjVYYc6Sd
Your method could be like this :
=> Future<TestModel> getAllData() async {
var result;
var request = await http.get(baseUrl);
if(request.statusCode == 200) {
result = testModelFromJson(request.body.toString());
} else {
print(request.statusCode.toString());
}
return result;
}

How to get the values from json object which is in the form Future<String>?

I am using aws_ai plugin and the response is in the form of
instance of Future<String>
I read the response as given below. I need to access specific value from json with key "confidence", how do I access it?
Future main1() async {
File sourceImagefile; //load source image in this File object
String accessKey = "",
secretKey = "",
region = "" ;
RekognitionHandler rekognition = new RekognitionHandler(accessKey, secretKey, region);
if(sourceImagefile !=null && targetImagefile !=null) {
Future<String> labelsArray = rekognition.compareFaces(
sourceImagefile, targetImagefile);
print(labelsArray);
return labelsArray.toString();
}else{
return "Enter Image";}
}
___________________________________
(later in widget build:)
___________________________________
onpressed(){
main1().then((labelsArray){
print("json value is: "+labelsArray);
});
}
the current result is :
json value is: Instance of 'Future<String>'
thanks for the help!
The reason you are getting the Instance of 'Future<String>' as a result is you are not waiting for the future to return and just getting the Future<String> object back refer this for more details:
The below code should solve your problem:
Future<String> futureFunction() async {
RekognitionHandler rekognition = new RekognitionHandler(accessKey, secretKey, region);
if(sourceImagefile !=null && targetImagefile !=null) {
var labelsArray = await rekognition.compareFaces(
sourceImagefile, targetImagefile);
print(labelsArray);
return labelsArray.toString();
} else {
return "enter image";
}
}

How to open csv file which contains special characters in one of the fields in csv?

hi I am working on a xamarin.forms app, While trying to open one of the csv file the following exception is displayed "input string is not in a correct format " the csv file contains a field called item name which consists the following names ET Door,E459-2,H 91 Ft and Key,Door so these both items contain comma so I am not able to open the csv file which consists of these two elements as they contain special characters like comma and underscore .Here is my code to read and open csv file ,please check the code and let me know what changes do i need to make so the file with items consisting of special characters also open ?
public async void OnProcess(object o, EventArgs args)
{
if (!string.IsNullOrWhiteSpace(csv_file.Text))
{
// _database.AddFiles();
if (App.Current.MainPage is NavigationPage)
{
try
{
List<ItemsCSV> items = new List<ItemsCSV>();
string[] lines = File.ReadAllLines(string.Format(#"{0}", this.file.FilePath));
if (lines != null)
{
for (int x = 1; x < lines.Length; x++)
{
string data = lines[x];
string[] item = data.Split(',');
// ItemsCSV itemsCSV = new ItemsCSV();
_itemsCSV = new ItemsCSV();
{
_itemsCSV.Cycle_Count = string.IsNullOrEmpty(item.ElementAtOrDefault(0)) ? 0 : Convert.ToInt32(item[0]);
_itemsCSV.Line_Number = string.IsNullOrEmpty(item.ElementAtOrDefault(1)) ? 0 : Convert.ToInt32(item[1]);
_itemsCSV.Item_Number = item.ElementAtOrDefault(2);
_itemsCSV.Name = item.ElementAtOrDefault(3);
_itemsCSV.Warehouse = item.ElementAtOrDefault(4);
_itemsCSV.Aisle = item.ElementAtOrDefault(5);
_itemsCSV.Bin = item.ElementAtOrDefault(6);
_itemsCSV.Level = item.ElementAtOrDefault(7);
_itemsCSV.Order_Qty = string.IsNullOrEmpty(item.ElementAtOrDefault(8)) ? 0 : Convert.ToInt32(item[8]);
_itemsCSV.Order_UOM = item.ElementAtOrDefault(9);
_itemsCSV.Consumption_Qty = string.IsNullOrEmpty(item.ElementAtOrDefault(10)) ? 0 : Convert.ToInt32(item[10]);
_itemsCSV.Consumption_UOM = item.ElementAtOrDefault(11);
_itemsCSV.Status = "";
};
items.Add(_itemsCSV);
_database.AddItems(_itemsCSV);
}
var result = await DisplayAlert("", "CSV has been processed, please do cycle count", "OK", "Cancel");
if(result == true)
{
var cyclecountPage = new CycleCountPage(items, 0, "MainPage",this.file.FilePath);
await (App.Current.MainPage as NavigationPage).PushAsync(cyclecountPage);
}
else
{
}
}
else
{
await DisplayAlert("Alert", "File is empty", "OK");
}
}
catch (Exception e)
{
await DisplayAlert("Exception", e.Message, "OK");
}
}
}
else
{
await DisplayAlert("Alert", "File name is mandatory", "OK");
}
}

WP8 Some images not downloading using HttpClient

I am building a WP8 app that downloads images using HttpClient in a background task. My problem is that some images are not downloaded no matter how much time I wait for them to finish. The image sizes are a few megabytes at maximum.
The code I use to download images:
internal static async Task<bool> Download_Wallpaper(string image_url, string file_name, string destination_folder_name)
{
try
{
using (var client = new HttpClient())
{
// 12MB max images
client.Timeout = TimeSpan.FromSeconds(5);
client.MaxResponseContentBufferSize = DeviceStatus.ApplicationMemoryUsageLimit / 2;
//client.Timeout = TimeSpan.FromSeconds(5);
byte[] image_byte_arr;
try
{
/* var requestMessage = new HttpRequestMessage( HttpMethod.Get, image_url );
var responseMessage = await client.SendAsync((requestMessage));
// byte array of image
image_byte_arr = await responseMessage.Content.ReadAsByteArrayAsync();
*/
// byte array of image
image_byte_arr = await client.GetByteArrayAsync(image_url);
}
// Could not download
catch (OutOfMemoryException X)
{
GC.Collect();
return false;
}
var folder = await StorageFolder.GetFolderFromPathAsync(destination_folder_name);
// Create file
StorageFile file = await folder.CreateFileAsync(file_name, CreationCollisionOption.ReplaceExisting);
using (var write_stream = await file.OpenStreamForWriteAsync())
{
write_stream.Write(image_byte_arr, 0, image_byte_arr.Length);
}
Console.WriteLine(DeviceStatus.ApplicationCurrentMemoryUsage);
return true;
}
}
catch (HttpRequestException X)
{
Console.WriteLine(X);
return false;
}
catch (OutOfMemoryException X)
{
GC.Collect();
return false;
}
catch (Exception X)
{
Console.WriteLine(X);
return false;
}
}
This is an example image that fails to download: https://upload.wikimedia.org/wikipedia/commons/9/95/Tracy_Caldwell_Dyson_in_Cupola_ISS.jpg
In my experience all wikimedia images fail to download for some reason.
I see no way of tracking download progress using HttpClient. Is there a way to do so?
Edit: It seems that setting the timeout does not have any function. The HttpRequestException is not thrown after 5 seconds.
Edit2: I tried a different approach, the one that anonshankar suggested. With that method the code would get stuck at the line:
byte[] img = response.Content.ReadAsByteArrayAsync();
So the HttpResponse arrives, but somehow the bytes could not be read out, no matter how much time I gave it. How could this even happen? The hard part is getting the response, reading out the bytes should be simple.
Again, this only happens with some images, most of them downloads correctly. One example is mentioned above.
I have modified my image downloader code, so that it times out after a few seconds. Here is my final code:
internal static async Task<bool> Download_Wallpaper(string image_url, string file_name, string destination_folder_name)
{
try
{
using (var client = new HttpClient())
{
// prevent running out of memory
client.MaxResponseContentBufferSize = DeviceStatus.ApplicationMemoryUsageLimit / 3;
byte[] image_byte_arr = null;
using (CancellationTokenSource cts = new CancellationTokenSource())
{
var task = Task.Factory.StartNew(() =>
{
try
{
image_byte_arr = client.GetByteArrayAsync(image_url).Result;
}
catch (AggregateException X)// Handling read errors, usually image is too big
{
Console.WriteLine(X.Message);
foreach (var v in X.InnerExceptions)
Console.WriteLine(v.Message);
image_byte_arr = null;
}
}, cts.Token);
bool finished_in_time = task.Wait(TimeSpan.FromSeconds(5));
if (!finished_in_time)// Timeout
{
cts.Cancel();
task.Wait();
return false;
}
else if (image_byte_arr == null)// Read error
{
return false;
}
}
var folder = await StorageFolder.GetFolderFromPathAsync(destination_folder_name);
// Create file
StorageFile file = await folder.CreateFileAsync(file_name, CreationCollisionOption.ReplaceExisting);
using (var write_stream = await file.OpenStreamForWriteAsync())
{
write_stream.Write(image_byte_arr, 0, image_byte_arr.Length);
}
Console.WriteLine(DeviceStatus.ApplicationCurrentMemoryUsage);
return true;
}
}
catch (HttpRequestException X)
{
Console.WriteLine(X);
return false;
}
catch (OutOfMemoryException X)
{
GC.Collect();
return false;
}
catch (Exception X)
{
Console.WriteLine(X);
return false;
}
}
Any improvement suggestions are welcome, and I still don't understand why does the method HttpContent.ReadAsByteArrayAsync() gets stuck.
Just try out this snippet which worked for me.
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("give the url");
byte[] img = response.Content.ReadAsByteArray();
InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
writer.WriteBytes(img);
await writer.StoreAsync();
BitmapImage b = new BitmapImage();
b.SetSource(randomAccessStream);
pic.Source = b; //(pic is an `<Image>` defined in the `XAML`
Hope it helps!