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
Related
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 to Convert this
[{destLocId=10, createdUserId=b9ab2d71-9a69-4ba3-b498-d36446a154d6,
createdDate=2016-6-29 14:35:00}]
to this :
[{"destLocId":10, "createdUserId":b9ab2d71-9a69-4ba3-b498-d36446a154d6,
"createdDate":2016-6-29 14:35:00}]
You can use GSON library for converting ArrayList to JSON. Here an example,
ArrayList<String> bibo = new ArrayList<String>();
bibo.add("obj1");
bibo.add("obj2");
bibo.add("obj3");
String json = new Gson().toJson(bibo);
And this example from Gson User Guide to use it on collection.
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);
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.
I'm using Gson in an Android app to convert a complicated object to JSON representation. One of the fields is a string called QuickPin containing an encrypted password and the character "=" is converted to "\003d" by Gson.
The Json string is consumed by a C# WEBAPI application, but returns "an error has occurred" message.
The following JSON returns that error message :
{"UserContractID":"929c1399-11c4-490e-8cff-5b1458ac18e2","UserAuthentication":"MethodCombo":{"AuthMethod":[1]},"QuickPin":"mW2n2uTECEtVqWA2B9MzvQ\u003d\u003d"},"CustomerID":0,"OriginID":0,"OriginTypeID":0,"Status":0}
Meanwhile this JSON works fine :
{"UserContractID":"929c1399-11c4-490e-8cff-5b1458ac18e2","UserAuthentication":{"QuickPin":"mW2n2uTECEtVqWA2B9MzvQ==","MethodCombo":{"AuthMethod":[1]}},"CustomerID":0,"OriginID":0,"OriginTypeID":0,"Status":0}
Are there a way to force Gson to maintain the string with the password with the = (and others if is the case) characters?
My Android code is :
Gson gson = new Gson();
user = new User();
user.UserAuthentication = new UserAuthentication();
user.UserAuthentication.QuickPin = "mW2n2uTECEtVqWA2B9MzvQ==";
user.UserAuthentication.MethodCombo = new MethodCombo();
user.UserAuthentication.MethodCombo.AuthMethod = new ArrayList<Integer>();
user.UserAuthentication.MethodCombo.AuthMethod.add(1);
user.Status = 0;
String jsonRepresentation = gson.toJson(user);
object.put("user", jsonRepresentation);
Thanks
Gson escapes HTML metacharacters by default. You can disable this behavior.
Gson gson = new GsonBuilder().disableHtmlEscaping().create();