Reputation: 85
How to save array into JSON and then make that JSON into string and save it into preferences Android. And after that be able to load string from preferences into JSON and then take the array. Since there are no JSONarrays in libgdx
Upvotes: 1
Views: 509
Reputation: 312
i think,
import com.badlogic.gdx.utils.Json;
and,
Json json = new Json();
create function to get libgdx preferences.
private Preferences getPreferences() {
return Gdx.app.getPreferences(PREFERENCES_NAME);
}
then, convert your array into string,
String str = json.toJson(yourArray);
last, pass the string into libgdx preferences using putString()
getPreferences().putString(ARRAY_JSON_PREFERENCES, str);
getPreferences().flush();
to get the array from the preferences.
String theArrayString = getPreferences().getString(ARRAY_JSON_PREFERENCES,json.toJson(defaultArray));
next, to build the theArrayString into array
int[] yourBuidArray = json.fromJson(int[].class, theArrayString);
or
String[] yourBuidArray = json.fromJson(String[].class, theArrayString);
Upvotes: 2
Reputation: 2330
I don't know exactly what you can do with libgdx, but if you are free to use external libs, you should use Gson. You serialize your object in json String with Gson, and then save it in preferences. Later, you make the "reverse".
private static String listToJson(List<?> list){
return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(list);
}
Then :
JSONObject myJson = new JSONObject(stringFromMyPreferences);
Upvotes: 0