Im get from my server an array of objects like this:
Log.i(TAG, "Destinos obtenidos: "+ destinosRuta);
Value of log -
Destinos obtenidos [{"Latitud":41.40404,"nombreDestino":"Barcelona","IDR":5,"IDD":6,"Longitud":2.168679},{"Latitud":37.408424,"nombreDestino":"Sevilla","IDR":5,"IDD":7,"Longitud":-5.9681},{"Latitud":38.92298,"nombreDestino":"Mérida","IDR":5,"IDD":4,"Longitud":-6.363121}]
which I want to stock on SharedPreferences, I have used the code from this answer:
But I don't know if i need to use an array of object, or I need to convert in an array of String, this is my code:
private Emitter.Listener onNuevaRuta = new Emitter.Listener() {
@Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
String destinosRuta = "";
try {
destinosRuta = data.getString("destinosRuta");
}catch (JSONException e) {
return;
}
//destinosRuta has the previous value
ArrayList<String> listaDestinos = new ArrayList<String>(Arrays.asList(destinosRuta));
setStringArrayPref(getApplicationContext(), "listaDestinos", listaDestinos);
listaDestinos = getStringArrayPref(getApplicationContext(), "listaDestinos");
String origen = listaDestinos.remove(0);
String destino = listaDestinos.remove(0);
setStringArrayPref(getApplicationContext(), "listaDestinos", listaDestinos);
...
And, like the previous link, I have used his function:
public static void setStringArrayPref(Context context, String key, ArrayList<String> values) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
JSONArray a = new JSONArray();
for (int i = 0; i < values.size(); i++) {
a.put(values.get(i));
}
if (!values.isEmpty()) {
editor.putString(key, a.toString());
} else {
editor.putString(key, null);
}
editor.commit();
}
public static ArrayList<String> getStringArrayPref(Context context, String key) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String json = prefs.getString(key, null);
ArrayList<String> destinos = new ArrayList<String>();
if (json != null) {
try {
JSONArray a = new JSONArray(json);
for (int i = 0; i < a.length(); i++) {
String destino = a.optString(i);
destinos.add(destino);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return destinos;
}
And i get an error when I'm tring to removed the first element of listaDestinos here:
String origen = listaDestinos.remove(0);
String destino = listaDestinos.remove(0); <--Error
FATAL EXCEPTION: main Process: tfg.clienteandroid, PID: 17276 java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.remove(ArrayList.java:403) at tfg.clienteandroid.mapaActivity$3$1.run(mapaActivity.java:320)
Any idea? I want to remove twice and be able to use both objects from my array.