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.
Related
I have a shopping cart where I want to remove a product there, but I'm facing an issue. I can add product to the shopping cart and I save to shared preferences, but when I want to remove it but doesn't work. Here what I did:
holder.removeProduct.setOnClickListener(v -> {
SharedPreferences preferences = mContext.getSharedPreferences(ITEMS_PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = preferences.edit();
Gson gson = new Gson();
String json = preferences.getString("artikujtShporta", "");
ArrayList<Artikujt> artikullObject = gson
.fromJson(json, new TypeToken<ArrayList<Artikujt>>(){}.getType());
if (artikullObject != null) {
artikullObject.remove(artikulli);
String jsonString = gson.toJson(artikullObject);
mEditor.putString("artikujtShporta", jsonString);
mEditor.apply();
} else {
ArrayList<Artikujt> arrayArtikuj = new ArrayList<>();
arrayArtikuj.remove(artikulli);
Type listOfTestObject = new TypeToken<ArrayList<Artikujt>>(){}.getType();
String s = gson.toJson(arrayArtikuj, listOfTestObject);
mEditor.putString("artikujtShporta", s);
mEditor.apply();
}
});
The same thing I did for adding the product, with the difference that here I call
artikullObject.remove(artikulli);
What i'm missing?
What is the problem?
The problem here will be that the instance of your class Artikujt which you want to delete from the Array is not the same as you have read out of the Preferences.
As soon as you use Gson to make your String to a new Array it will generate completely new instances of your class and obviously these will not be the same as you had before. Maybe they are equal, but they are not the same instances.
What can you do to solve this?
I am assuming that you want to have each Artikujt only once. What means you could also use a HashSet. The advantage of this is it would would use the hashCode() function to determine which instance in the set you want to remove. So you just need to override this hashCode() function in your model class and use all of its properties to calculate the hashcode. You can find a example here: https://www.sitepoint.com/how-to-implement-javas-hashcode-correctly/
Sidenote
Your else block is unnecessary. It doesn't make a lot of sense. You are creating a empty ArrayList, then you remove sth from this empty list and then you save this empty List into the shared preferences. The logic of your code wouldn't change if you would just remove this else block.
In my Android app i archive large amount of data as json in my SharedPreferences, the json items are build as the following {"codiceArticolo":"0401100028053","data":"mer 03/07/2019","qta":"1"} there could be more than 500 items like this in the JSON.
Actually the json is generated from an ArrayList from the following method
public void saveStorico(){
ArrayList<ItemModel> itemToRemove = new ArrayList<>();
ArrayList<ItemModel> itemToAdd = new ArrayList<>();
// various controlls
for(ItemModel itemModels : itemModel){
boolean exist = false;
for(ItemModel itemModel2 : itemStorico){
if(itemModels.getCodiceArticolo().contains(itemModel2.getCodiceArticolo())) {
itemToRemove.add(itemModel2);
itemToAdd.add(itemModels);
exist = true;
}
}
if(!exist) {
itemToAdd.add(itemModels);
}
}
itemStorico.removeAll(itemToRemove);
itemStorico.addAll(itemToAdd);
SharedPreferences sharedPreferences = getSharedPreferences("STORICO_ORDINI", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(itemStorico);
editor.putString("storico", json);
editor.apply();
}
But i'm having some issues when i fetch that data it seems that some of saved items just are not being saved, could there be a max lenght limit that i could save inside sharedpreferences as json?
If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs.
For large amounts of data as in your case, SharedPreferences is not a good choice.
You should rather be using a SQL database or a NoSQL database instead.
As per what I have seen before, if the shared preferences go beyond 100kb, you need to consider alternatives. And if it exceeds ~1MB, there potentially can be out of memory exceptions.
I have made a test activity that stores your marks in shared preferences and then I want those marks to be shown in another activity as a list, Being a newbie I think I have to append the initial score value into another shared preference and even after days of trying I am unable to get it done.
I have already seen similar questions asked on the site and none of them gave me exactly what I want. What do I need to do in that case? Please provide a snippet of code to guide me through.
Using Gson for saving Result value in key and object without append string.
put gson Gradle file in Gradle. main
implementation 'com.google.code.gson:gson:2.8.0'
Save Result in SharedPreferences:
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject);
prefsEditor.putString("Key", "Value");
prefsEditor.commit();
get value from SharedPreferences:
Gson gson = new Gson();
String json = mPrefs.getString("Key", "");
MyObject obj = gson.fromJson(json, MyObject.class);
Download Github code FromHere
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.