2

Say my storage looks like this:

1 - turkey
2 - chicken
3 - beef
4 - fish

If I delete chicken, I'd want to update it to:

1 - turkey
2 - beef
3 - fish

I also need a way to re-order, so if I say fish should be first, I'd want it to update to:

1 - fish
2 - turkey
3 - beef

What is the best way to go about doing this?

Roger
  • 4,249
  • 10
  • 42
  • 60

2 Answers2

2

Store and retrieve JSON arrays and manipulate your list using the List interface:

String listToJson(List<String> list) {
  JsArrayString array = (JsArrayString) JsArrayString.createArray();

  for (int i = 0; i < list.size(); i++) {
    array.set(i, list.get(i));
  }

  return new JSONArray(array).toString();
}

List<String> jsonToList(String json) {
  JsArrayString jas = JsonUtils.safeEval(json);
  List<String> list = new ArrayList<String>();

  for (int i = 0; i < jas.length(); i++) {
    list.add(jas.get(i));
  }

  return list;
}

void myEntryPoint() {
  ArrayList myList = new ArrayList();
  myList.add("cake");
  myList.add("pie");
  myList.add("ice cream");

  Storage.getLocalStorageIfSupported().
      setItem("myKey", listToJson(myList));

  // ...

  ArrayList otherList =
      jsonToList(Storage.getLocalStorageIfSupported().
          getItem("myKey"));
}
Jason Terk
  • 6,005
  • 1
  • 27
  • 31
  • 1
    Instead of `JSONParser.parseString`/`isArray`/`getJavaScriptObject`, use `JsArrayString jas = JsonUtils.safeEval(json);`; easier to read and a bit cheaper (no need to check the type of the result and create a JSONArray wrapper). – Thomas Broyer Nov 23 '11 at 17:15
0

The only way I can think of is to use an array.

localstorage.list = [turkey, chicken, beef, fish];

This will give a start value of 0 for turkey, you could manually set the index to 1 for turkey, 2 for chicken etc.

To remove an item you would need to slice that item:

list.splice(1); //removes chicken

To shuffle it have a look at this post which explains it pretty well.

Community
  • 1
  • 1
  • LocalStorage should not be used by setting properties on the `localstorage` object. [The API](https://developer.mozilla.org/en/DOM/Storage) defines `getItem(key)`, `setItem(key, value)` and `removeItem(key)` functions for manipulating key/value pairs. Both the keys and values must be strings. – Jason Terk Nov 23 '11 at 17:12