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
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);
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);
Related
my question is about the following.
Im just trying to generate a new txt file in my internal storage. Inside it i will have just an array converted to string to save some IDs that i need to persist.
After that i need to read that file too but i don't know how to start.
I think is something like this:
private void GsonWriter(ArrayList<Integer> arrayListTouched){
String str = arrayListTouched.toString();
Gson gson = new GsonBuilder().create();
Since you're already using Gson.
How to save it.
Gson gson = new GsonBuilder().create();
ArrayList<Integer> array = new ArrayList<>(); // Integer in your case. But can be any type
// save this string
String arrayString = gson.toJson(array);
How to load it.
ArrayList<Integer> array = gson.fromJson(arrayString, new TypeToken<ArrayList<Integer>>(){}.getType());
I assume you know how to save/load the string
I want to remove attributes that I specify collections using Gson.
My code:
SharedPreferences sharedPreferences = parentActivity.getSharedPreferences(Accommodation.UPLOAD_ACCOMMODATION_DETAILS_ALL, MODE_PRIVATE);
// Get saved string data in it.
String userInfoListJsonString = sharedPreferences.getString(Accommodation.UPLOAD_ACCOMMODATION_DETAILS, "");
// Create Gson object and translate the json string to related java object array.
Gson gson = new Gson();
Accommodation userInfoDtoArray = gson.fromJson(userInfoListJsonString, Accommodation.class);
// Loop the UserInfoDTO array and print each UserInfoDTO data in android monitor as debug log.
// Get each user info in dto.
Accommodation userInfoDto = userInfoDtoArray;
I printed Json and it have this:
{"accommodationName1":"Green Flat",
"accommodationName2":"Bangolor",
"accommodationName3":"GHost house",
"imgAccommodation1":"/data/user/0/com.xxx.xxx/cache/cropped6900224487159235524.jpg",
"imgAccommodation2":"/data/user/0/com.xxx.xxx/cache/cropped3411178797945328810.jpg",
"imgAccommodation3":"/data/user/0/com.xxx.xxx/cache/cropped9128365945226539316.jpg"}
I can use this code to get the value:
userInfoDto.accommodationName1;
It show the value :
Green Flat
So how I can remove the specific collection of that value?
In my app, I need some data that I do not want to request every time from the server.
This dat includes the userId and some array string.
I think I can store the user id in the SharedPreferences,
but what about the array?
Is it OK to use static variables?
You also can serialize your array to save a array as string in preferences, but keep in mind that if it was big, use Sqllite...
Or you can use the firebase with offline function.
You can use Gson parse Array to String and save to shared preferences.
When you read String from shared preferences you can use Gson to convert String to Array.
Gson library
ArrayList<String> yourArrayStr = convertArrayToString(yourArray);
SharedPreferences prefs = context.getSharedPreferences("PREFERENCE_NAME",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("array_key_name", yourArrayStr);
editor.apply();
function: convertArrayToString
private String convertArrayToString(ArrayList<String> yourArray){
Gson gson = new Gson();
return gson.toJson(yourArray);
}
function convertStringToArray when you read String from shared preferences
private ArrayList<String> convertStringToArray(String yourArrayStr){
Gson gson = new Gson();
return gson.fromJson(yourArrayStr , new TypeToken<ArrayList<String>>(){}.getType());
}
Good luck!
First of all create a class model. like this
public class User implements Serializable {
#SerializedName("id")
private int id;
#SerializedName("array")
private ArrayList<String> array;
//your get/set are here too
}
I use gson to make my life easier.
Than on your server response save the Json on your SharedPreference
SharedPreferencesUtils.write(Constants.Preferences.Keys.USER_DATA, userJson);
And finally everytime you need to read this information you use
String json = SharedPreferencesUtils.read(Constants.Preferences.Keys.USER_DATA, null);
User user = new Gson().fromJson(json, User.class);
I would load this information on your singleton to use everywhere i need it in the application :)
If you need to update it.. just get the response and save again on your SharedPreference.
How i can pass ArrayList<byte[]> to JSONObject as a parameter?
For example, I need to send a Id (string), Name (string) and photoList (ArrayList<byte[]>) in a json object.
You can use GSON LIBRARY . The code you need can be as :
String jso;
jso = new Gson().toJson(photoList);
It should convert the arraylist(i.e. photoList) to jsonObject.
Just use GSONlib for this if you want to convert arraylist into json
If you are using GSON library use the following code to convert your ArrayList to JSON.
String jsonString = new Gson().toJson(yourArrayList);
Basically I have an app that fetches some information from Facebook, and that info can be regularly updated. I want to save that information in the phone so that when the user does not have an internet connection he can still see the latest fetch.
The information is saved in a
ArrayList<HashMap<String, String>>
What should I use?
The amount of information to save is small. 7 entries in the HashMap and at most 15 in the ArrayList. I use this datatype because I display it in a ListView.
Again that info must be saved even is the app is closed.
Regards
you can write it to a json or xml file , and load that file when app started
I think the best way is to save it to SharedPreferences. An easy way is to convert this object to JSON String and store that String in the SharedPreferences, and then when needed, get JSON string back and convert it back to your object. The library that does it nicely is Google's gson library. If you are using Gradle, import it like this:
dependencies {
...
compile 'com.google.code.gson:gson:2.2.+'
...
}
then, you can use this simple class to convert objects to/from String
public class JsonHelper {
public static Gson gson = new GsonBuilder()
.setPrettyPrinting().create();
public static Object getObject(String jsonString, Type classType){
return gson.fromJson(jsonString, classType);
}
public static String getJsonString(Object object){
return gson.toJson(object);
}
}
then, you can do this:
//to get JSON string from your object
ArrayList<HashMap<String, String>> yourList = ...;
String JSONString = JsonHelper.getJsonString(yourList);
//save string to shared preference
//to get your object from JSON string
//get JSON string from shared prefs
String yourJsonString = ...;
Type t = new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType();
ArrayList<HashMap<String, String>> yourList = (ArrayList<HashMap<String, String>>)JsonHelper.getObject(yourJsonString, t);
here is some info about SharedPreferences and some info on how to use SharedPreferences, its really easy.
Then, you can add these methods to your Activity
public class YourActivity extends Activity{
public static final String KEY_PREFS = "com.your_app_name";
public static final String KEY_DATA = "your_data";
...
public static void saveDataToPrefs(String json){
getSharedPreferences(KEY_PREFS, Context.MODE_PRIVATE).edit().putString(KEY_DATA, json).commit();
}
public ArrayList<HashMap<String, String>> getDataFromPrefs(){
Type t = new TypeToken<ArrayList<HashMap<String, String>>>() { }.getType();
return (ArrayList<HashMap<String, String>>)JsonHelper
.getObject(getSharedPreferences(KEY_PREFS, Context.MODE_PRIVATE)
.getString(KEY_DATA, ""), t);
}
}
Please note this is not the best way to save the info in the app persistantly, as this method can produce unexpected bugs, like in case the final JSON string needs to be larger then the String object in the Android system. The best way is to have a database.
Have you looked at serialisation before? I find it very useful for this type of thing.
What is object serialization?
You can serialise out your data into an arbitrary file on the device SD card for example, then just read it back in on startup. I've used it for storing data in games, e.g. a save file.