Flutter - how to store lists of Strings: (GetStorage or Shared Preferences). using android - list

So, I have come across a solution for this problem using Get_storage thanks to a couple of great explanations about the topic. I managed to work with getx and the Provider package to save data when adding new stuff and reading it when starting the application (thats the behavior i'm going for here). Said that, i'm having a hard time trying to remove data from memory.
Context
The project is a to-do list app, the front end is working perfectly, but when it comes to storage it gets more complicated. The thing is that i'm very new to flutter and mobile development, i recieved some help but this kind of stuff is still foggy in my brain, i could not remove data using the same logic. When i called box.Remove('key') like the docs say, my ENTIRE list got removed. I don't have a single clue why that happaned.
And so i wonder if i could understand it more by reading through some more explanations, i know Shared Preferences is a great deal do work with this kind of situation, but i would also be confortable with a solution using get_storage since i'm more familiar with it.
the code:\
I'm calling these lists inside a listView on a different file with the help of Provider - -
List<Task> _tasks = [
Task(
name: "Title",
description: "Description",
),
];
Adding tasks to my ListView - -
void add(String newTitle, newDesc) {
final task = Task(name: newTitle, description: newDesc);
_tasks.add(task);
notifyListeners();
}
Here is the removal of a task from the ListView - -
void removeTasks(Task task) {
_tasks.remove(task);
notifyListeners();
}
I tried to implement a logic to write and read data, it worked. But i also tried to use this removeTasks method to remove from storage as well by calling box.Remove('tasks'); ('tasks' was the key passed to the writing and reading methods). It removed everything from memory since my listview got empty.
Since i'm not that experienced, i went through the documentation and could understand some of the SharedPreferences Explanation (same with got_storage) but i'm having a hard time when trying to apply it to my code.
I would appreciate any help using get_storage OR shared preferences to this problem.
Where i'm calling the deletion:
// bool variables that control the state of the screen
// since i can change it to show done tasks or on goind tasks
// dont mind that, i think its irrelevant to the problem.
//
bool isActiveDoing = true;
bool isActiveDone = false;
List finalArray = []; //it will store the tasks
class TaskList extends StatefulWidget {
#override
_TaskListState createState() => _TaskListState();
}
class _TaskListState extends State<TaskList> {
#override
Widget build(BuildContext context) {
//dont mind the if else as well, its not part of the problem
//just using it to handle the state of the screen
if (isActiveDoing) {
finalArray = Provider.of<TasksFunctions>(context).tasks;
}
//TasksFunctions is a class with methods on regards to the storage
//it contains add tasks, remove, etc... i'm using provider to
//link those to the screens with the notifyListeners
if (isActiveDone) {
finalArray = Provider.of<TasksFunctions>(context).doneTasks;
}
//now here is where i call the class tha has the deletion method
return Consumer<TasksFunctions>(
builder: (context, tasksFunctions, child) {
return ListView.builder(
//list view tha has all the tasks
itemCount: finalArray.length,
itemBuilder: (context, index) {
final task = finalArray[index];
//using the slidableWidget to wrap the deletion method
return SlidableWidget(
onDismissed: (action) {
if (isActiveDoing) {
Provider.of<TasksFunctions>(context, listen: false)
.removeTask(task);
//so here is where i'm deleting those tasks, calling that method
//listed up on this post
}
if (isActiveDone {
Provider.of<TasksFunctions>(context, listen: false)
.removeDone(task);
}
},
);
},
);
},
);
}
}
So i spent some time translating the code, but i think that it does not match any of flutter's good practices principles.
I also tried calling storageList.remove(task); and then rewriting it with the box.write('tasks', storageList); but nothing was removed from the memory (maybe because i didn't loop through the whole storageLists searching for the right index i guess)

Sounds like your code is based on my answer to your original question about this.
If that's the case, then the key tasks is the key to the entire list of maps, not a single map or Task. So it's behaving as expected when it wipes all of your tasks.
In order to persist any changes, you'd have to remove that particular map (Task) from storageList then overwrite the box again with box.write('tasks', storageList); It will save over the same list of maps and persist any deletions you made.
If you share your code where you're trying to delete the task and whats going on around it I can give you a more specific example.
EDIT: Answering question in comments.
If you wanted to go the UniqueKey route you wouldn't need the index at all. You could do something like this.
class Task {
final String name;
final String description;
final String key; // not an actual Key but will take the String value of a UniqueKey
Task({this.key, this.name, this.description});
}
When you add a new Task it would look like this.
final task = Task(
description: 'test description',
name: 'test name',
key: UniqueKey().toString());
Then you could use a Map of maps instead of a list of maps and use the key for both.
Map storageList = {};
void addAndStoreTask(Task task) {
_tasks.add(task);
final Map storageMap = {}; // temporary map that gets added to storage
storageMap['name'] = task.name;
storageMap['description'] = task.description;
storageMap['key'] = task.key;
storageList[task.key] = storageMap; // adding temp map to storageList
box.write('tasks', storageList); // adding map of maps to storage
}
Then your restore function would look like this:
void restoreTasks() {
storageList = box.read('tasks'); // initializing list from storage
storageList.forEach((key, value) { // value here is each individual map that was stored
final task =
Task(name: value['name'], description: value['description'], key: key);
_tasks.add(task);
});
}
Then when you go to delete, you iterate through the list and find the matching key.

Related

Osmdroid 5.6, offline MBTiles

I'm trying to use MBtiles offline with osmdroid,
I took code sample from here https://github.com/osmdroid/osmdroid/blob/master/OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/tileproviders/SampleOfflineOnly.java
But always empty map shown, is there problem with my code?
my code is:
public class OSMDroid extends AppCompatActivity {
private MapView mapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_osmdroid);
mapView = (MapView) findViewById(R.id.map);
String name = "map.mbtiles";
File f = new File(Environment.getExternalStorageDirectory() + "/osmdroid", name);
if (f.exists()) {
try {
//ok found a file we support and have a driver for the format, for this demo, we'll just use the first one
//create the offline tile provider, it will only do offline file archives
//again using the first file
OfflineTileProvider tileProvider = new OfflineTileProvider(new SimpleRegisterReceiver(this),
new File[]{f});
//tell osmdroid to use that provider instead of the default rig which is (asserts, cache, files/archives, online
mapView.setTileProvider(tileProvider);
//this bit enables us to find out what tiles sources are available. note, that this action may take some time to run
//and should be ran asynchronously. we've put it inline for simplicity
String source = "";
IArchiveFile[] archives = tileProvider.getArchives();
if (archives.length > 0) {
//cheating a bit here, get the first archive file and ask for the tile sources names it contains
Set<String> tileSources = archives[0].getTileSources();
//presumably, this would be a great place to tell your users which tiles sources are available
if (!tileSources.isEmpty()) {
//ok good, we found at least one tile source, create a basic file based tile source using that name
//and set it. If we don't set it, osmdroid will attempt to use the default source, which is "MAPNIK",
//which probably won't match your offline tile source, unless it's MAPNIK
source = tileSources.iterator().next();
mapView.setTileSource(FileBasedTileSource.getSource(source));
} else {
mapView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
}
} else {
mapView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
}
mapView.setUseDataConnection(false);
mapView.setBuiltInZoomControls(true);
IMapController mapController = mapView.getController();
mapController.setZoom(10);
GeoPoint startPt = new GeoPoint(61.5797,51.5997);
mapController.setCenter(startPt);
mapView.invalidate();
return;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
MBTilesFileArchive getTileSources always returns empty string, here is implementation:
public Set<String> getTileSources(){
//the MBTiles spec doesn't store source information in it, so we can't return anything
return Collections.EMPTY_SET;
}
In order to make a offline map you should add tiles first. You can use Maperitive app to make your map tiles(zip is easier to manage than sql). Name the zip MapquestOSM. After you have done it create a folder "osmdroid" in phones memory(Directly into the internal memory or sd card) and add your map tiles in it.
Parameters of the XYTileSource changes related to the map tiles you have created. This code handles everything about map tiles itself. I hope it helps you
mapView.setUseDataConnection(false);
mapView.setTileSource(new XYTileSource("MapquestOSM", 2, 15, 256, ".png", new String[]{}));

QML Map: Large amount of displayed items

I have a performance issue while displaying large amounts MapItems on a Map provided by the QML Location module. I already asked the question here (https://forum.qt.io/topic/79229/large-amount-of-qml-mapitems), but nobody could help me, so I wanted to try it here once. I also found this question (How to use the QML/QtLocation module for displaying a large amount of offline data on a map?), but before adding another dependency, I wanted to see if my code can be improved so that QML can handle this situation without any help.
I am currently trying to plot a large amount of items onto a QML Map (30,000 - 120,000 points). These items shall be updated dependent of the position of a QSlider. Performance decreases strongly from about 1,000 items upwards, when I use 30,000 it takes several minutes until the QML Map has all the data visualized and is responsive again. I have a machine which is absolutely capable of fulfilling this task in general, so I think the problem is QML. I am using Qt 5.8.
Is there any way to improve this performance or is it just not possible with a QML-map to plot so many MapItems at a time? I tried MapCircles, Polylines, Polygons and MapQuickItems with images, but for me it seems like the performance issue just arises from adding this amount of MapItems, as I could not see a significant difference in processing time between these types.
I have more data on the map visualized, which should not be refreshed every time the QSlider is moved. Even though I tried just to clear all MapItems and add the new ones for performance tests, but even this did not improve the performance.
My code (a bit abstracted) looks like this:
///-------------- Widget.cpp-----------------///
void ProcessInput(int qslider_pos) {
QVariantList lat_vec;
QVariantList lon_vec;
// Fill vectors with lateral and longitudinal positions
// ...
// Clean current points on map and draw new ones
SendToQmlFuncRemovePoints();
SendToQmlFuncAddPoints(lat_vec, lon_vec);
}
void QmlConnector::SendToQmlFuncRemovePoints()
{
QVariant returnedValue;
QMetaObject::invokeMethod(QmlMapSingleton::instance()->GetRoot(), "remove_points",
Q_RETURN_ARG(QVariant, returnedValue));
}
void QmlConnector::SendToQmlFuncAddPoints(QVariantList input_one, QVariantList input_two)
{
QVariant returnedValue;
QMetaObject::invokeMethod(QmlMapSingleton::instance()->GetRoot(), "add_points",
Q_RETURN_ARG(QVariant, returnedValue),
Q_ARG(QVariant, QVariant::fromValue(input_one)), Q_ARG(QVariant, QVariant::fromValue(input_two)));
}
.
///-------------- Map.qml -----------------///
Map {
anchors.fill: parent
property variant points: ({})
property int pointCounter: 0
Plugin
{
id: osmplugin
name: "osm"
PluginParameter { name: "osm.mapping.highdpi_tiles"; value: true }
}
Component.onCompleted: {
points = new Array();
}
id: map
plugin: osmplugin
//Javascript functions
function add_points(array_lat, array_lon) {
var myArray = new Array()
var component = Qt.createComponent("mapcircle.qml");
for (var i=0; i<array_lat.length; i++)
{
var object = component.createObject(map, { "center": QtPositioning.coordinate(array_lat[i], array_lon[i]})
map.addMapItem(object)
myArray.push(object)
}
map.points = myArray
}
function remove_points() {
var count = map.points.length
for (var i = 0; i<count; i++){
map.removeMapItem(map.points[i])
map.points[i].destroy()
}
map.points = []
}
}
.
///-------------- mapcircle.qml -----------------///
import QtQuick 2.0
import QtLocation 5.6
MapCircle {
radius: 1
border.width: 0
color: 'green'
}
Qt says that the performance decreases with the number of elements added to the map. Do you need all the points to be visible on the map in the same time, if not you can play around with visibility.
Can't you use QQuickPaintedItem to paint the points in C++ and wrap it into an MapQuickItem, if you have multiple polygonsfor e.g? But also there are some limitation, you cannot have to big images displayed.
If you need all the points maybe you can have different points based on the map zoom level and reduce the number of points added to the map at small zoom level, as was recommended on the other group ...

Sitecore, moving item takes multiple tries

I have a saving event handler in Sitecore where when the date of an item changes (from say 8/7/2014 to 9/7/2014) I want it to be moved into another folder.
It currently somewhat does that, but only if I change the date twice.
If I go from 8/7/2014 > 9/6/2014 it does nothing. If I then change the same item's date to 9/7/2014 it moves it into the correct folder.
If I debug the code it follows the exact same path both times .. anyone have a reason as to why this might be happening?
One of the other problems was that the saving handler was running twice, once with the new date value, once with the old. Changing to the saved handler worked much better because I only have access to the newly saved values, not the old and new values.
Since there were a few comments asking for it, here's the working code to move and item from folder parent to parent > year > month. Keep in mind this is using glassmapper so it would be slightly different if not using glass mapper.
protected void MoveItemToMonthDateFolder<T>(T scItem, Func<T, DateTime> dateSelector, Models.Item parentFolder) where T : Models.Item
{
var date = dateSelector(scItem);
if (!parentFolder.Children.Any(x => x.Name.Contains(date.Year.ToString())))
{
var yearFolder = sitecoreService.Create(parentFolder, new Folder { Name = date.Year.ToString() });
var monthFolder = sitecoreService.Create(yearFolder, new Folder { Name = date.Month.ToString() });
sitecoreService.Move(scItem, monthFolder);
}
else
{
var yearFolder = parentFolder.Children.First(x => x.Name.Equals(date.Year.ToString(), StringComparison.CurrentCultureIgnoreCase));
var monthFolder = yearFolder.Children.FirstOrDefault(x => x.Name.Equals(date.Month.ToString(), StringComparison.CurrentCultureIgnoreCase));
if (monthFolder == null)
{
monthFolder = sitecoreService.Create(yearFolder, new Folder { Name = date.Month.ToString() });
}
sitecoreService.Move(scItem, monthFolder);
}
}

WICKET: Updating a self-made Panel

ive got the following Problem:
my self-made video-class (extending Panel) doesnt get updated, if its model changes.
Thats the current state:
I got a Class "A" with a ListChoice. This Class creates the Panel "descrPanel", which gets a Model, containing the current selected Item of the ListChoice. It is updated, when the User selects something in the ListChoice (The ListChoice got an AjaxBehaviour, updating the descrPanel via target.add(descrPanel)):
Class A:
PropertyModel<Exercise> currExerciseModel = new PropertyModel<Exercise>(this,"selectedExercise");
final ExerciseDescriptionPanel descrPanel = new ExerciseDescriptionPanel("descrPanelTag", currExerciseModel);
descrPanel.setOutputMarkupId(true);
In Class ExerciseDescriptionPanel, i inserted my self-made Video-Class (extending Panel). Also i inserted a MultiLineLabel:
Class ExerciseDescriptionPanel
public class ExerciseDescriptionPanel extends Panel {
private IModel<Exercise> model;
private Exercise exercise;
public ExerciseDescriptionPanel(String id, IModel<Exercise> model) {
super(id, model);
this.model = model;
MultiLineLabel mll = new MultiLineLabel("mll", new Model() {
#Override
public String getObject() {
if (ExerciseDescriptionPanel.this.getModel().getObject() != null){
return ExerciseDescriptionPanel.this.getModel().getObject().getDescription();
}
else return "";
}
});
add(mll);
Video video = new Video("myVideo", new Model<Exercise>(){
#Override
public Exercise getObject() {
if (ExerciseDescriptionPanel.this.getModel().getObject() != null){
return ExerciseDescriptionPanel.this.getModel().getObject();
}
else return new Exercise();
}
});
add(video);
}
Well, what i dont understand is: While the Description is updated based on the current selection of the ListChoice, the Video-Class just ignores it and keeps returning the "new Exercise()", which schould only be returned at the first load of the ListChoice, when no selection is made.
I also provide you the Video-Class:
Class Video
public class Video extends Panel{
private IModel<Exercise> model;
public Video(String id, IModel<Exercise> model) {
super(id, model);
String src = ((Exercise)model.getObject()).getVideo();
String startPicDest = ((Exercise)model.getObject()).getPicture();
WebMarkupContainer flashSrc = new WebMarkupContainer("flashSrcTag");
flashSrc.add(new AttributeModifier("value", "config={'playlist':['" +
startPicDest +"',{'url':'"+ src +"','autoPlay':false}]}"));
this.add(flashSrc);
setOutputMarkupId(true);
}
}
Ive been searching through the internet for hours now, without finding anything helpful.
Hope you guys are able to give me some solution to this problem. Thanks in regard.
Greetings
You're pulling the exercise out of the model once only:
public Video(String id, IModel<Exercise> model) {
super(id, model);
String src = ((Exercise)model.getObject()).getVideo();
...
}
How is this supposed to be up-to-date when the exercise changes later on?
You have to get the actual value for each render:
WebMarkupContainer flashSrc = new WebMarkupContainer("flashSrcTag") {
public void onComponentTag(ComponentTag tag) {
Exercise temp = (Exercise)model.getObject();
String src = temp.getVideo();
String startPicDest = temp.getPicture();
tag.put("value", String.format("config={'playlist':['%s',{'url':'%s','autoPlay':false}]}", startPicDest, src));
}
};
NOTE: Please ignore this humble try to help you, svenmeier's answer is way better than mine.
I'm not 100% sure if this is true, but could it be related to the difference between your Video being a MarkupContainer and the MultiLineLabel being a WebComponent?
Both the Video and the MultiLineLabel are added to the ExerciseDescriptionPanel in its constructor. If I understand the Wicket documentation correctly, as long as the surrounding Page and thus the ExerciseDescriptionPanel stay the same instance, the markup of the Video will not be regenerated. It says:
A Page renders itself by rendering its associated markup (the html file that sits next to the Page). As MarkupContainer (the superclass for Page) iterates through the markup stream for the associated markup, it looks up components attached to the tags in the markup by id. Since the MarkupContainer (in this case a Page) is already constructed and initialized by onBeginRequest(), the child for each tag should be available in the container. Once the Component is retrieved, it's render() method is called.
Maybe you calling modelChanged() on your Video once you change the Model of your ExerciseDescriptionPanel could indicate that the markup has to be refreshed.

Why can't I delete a property in a map function, in CouchDB?

I've got a view and a map function, in CouchDB. I'm simply iterating over some values in an array, an emitting them individually. I'd like to exclude a property of the documents that I am emitting, though. I was hoping to just call delete on it, but that doesn't appear to be doing anything. The value is still emitted with the property. Is this a limitation in order to keep indexing fast? My map function looks like this:
function(doc) {
if (doc.type == 'user' && doc.spaces) {
doc.spaces.forEach(function (space) {
if (space.tokens) {
space.tokens.forEach(function (token) {
emit(token.token, space);
});
}
});
}
}
Where I emit space, I'd like to delete the tokens property of it, before emitting. I don't want to expose other tokens in this data. So, I modified to code to look like this, with no luck. It still emits the full document, with tokens intact:
function(doc) {
if (doc.type == 'user' && doc.spaces) {
doc.spaces.forEach(function (space) {
if (space.tokens) {
var tokens = space.tokens;
delete space.tokens;
tokens.forEach(function (token) {
emit(token.token, space);
});
}
});
}
}
It happened the same trouble for me, now. And I was search the topic. But unfortunately, the other answer was not useful for me. Because, CouchDB is not SQL, documents has a different properties. Therefore I cannot emit with a specific properties.
After thinking, I hit on an idea for the problem. It is there:
function( doc )
{
// Remove a `seal` in the doc using a deep-copy technique.
var tmp = JSON.parse( JSON.stringify( doc ) );
// We can `delete` a property as we like!
delete tmp._rev;
// Emit `tmp`.
emit( null, tmp );
}
We've been bitten by this problem as well.
We worked around it by creating a new object and emitting that instead:
emit(token.token, {
name : space.name,
id : space.id
etc : etc
}
We found that was the best way anyway as most of the time there was no need to emit complete (child) documents and only what was required.