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
Related
i create app where when user added new data , there is new label
I have tried and it worked, but I wonder how can I make the json that I store in SharedPreferences
do not over write
so I can add 2 or more user json to adapter
Here is my put string file the json variable contain user that added
SharedPreferences sharedPreferences = getSharedPreferences("newUser", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("listNewUser",json)
editor.apply();
Here is how I can get json from shared preference
try{
String listNewUserAdd = sh.getString("listNewUser","");
JSONObject object = new JSONObject(listNewUserAdd);
for (int i=0; i<object.length(); i++) {
CustomerNew customer = new CustomerNew();
customer.setCustomerName(object.getString("receiverName"));
customer.setAccountId(object.getString("customerReference"));
customer.setId(object.getLong("customerId"));
System.out.println("### GET CUSTOMER NAME "+customer.getCustomerName());
listSortNew.add(customer);
if (listSortNew == null) {
// if the array list is empty
// creating a new array list.
listSortNew = new ArrayList<>();
}
}
I think there are two ways to realize it. One way is when you put data you have to check if it exists.
SharedPreferences sharedPreferences = getSharedPreferences("newUser", MODE_PRIVATE);
String listNewUser = sharedPreferences.getString("listNewUser","");
if(!TextUtils.isEmpty(listNewUser)){
//covert it the list object
//then add the all new item to it
//finally convert it to json string
}
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("listNewUser",json)
editor.apply();
the other way is to change the SharedPreferences MODE_APPEND
but you must know, it doesn't mean that you add multiple values for each key. It means that if the file already exists it is appended to and not erased. We usually used MODE_PRIVATE
In the end I suggest you firstly get the data from it, then check if you need change, you can change the data, then save it again.
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.
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.
I have an ArrayList that can contain 1 to 15 strings. Those strings need to be saved in my shared preferences, now I know how to iterate trough the array to get the strings. What I don't know, is there a clean way to dynamically add the strings to my shared preferences file? I could do this on a sluggish way by creating 15 strings and using an if statement to fill the shared preference, but I would like to know if there is a better way.
Thank you.
If its about naming, you can use something like this:
public static final String mPrefix = "mArray";
SharedPreferences prefs;
prefs = this.getSharedPreferences("PREF", 0);
prefsEditor = appSharedPrefs.edit();
//mAL is your ArrayList
for(int i=0; i<mAl.size(); i++){
prefsEditor.putString(mPrefix + "-" + i, mAl.get(i));
}
prefsEditor.commit();
You can use the putStringSet method available in SharedPreferences.Editor to store string arrays. For example:
String[] array = new String[]{"this", "is", "a", "string", "array"};
SharedPreferences.Editor edit = sharedPrefs.edit();
edit.putStringSet("myKey", new HashSet<String>(Arrays.asList(array)));
edit.commit();
Or if your API is below 11 then you may convert your string array into a single string and save it just like an ordinary string. For example:
edit.putString("myKey", TextUtils.join(",", array));
and later use the following to rebuild your array from string:
array = TextUtils.split(sharedPrefs.getString("myKey", null), ",");
Mainly to edit the shared prefernces data you need to take the Editor Object from it so you could edit it freely so to put data in it:
SharedPrefernces preferences = mContext.getSharedPreferences(MODE_PRIVATE);
Editor prefEditor = preferences.edit();
prefEditor.putString("this is a key object","this is value of the key");
You can also put inside different kinds of object for example : boolean , int , float , double and etc....
Just look up the editor class in android developers website...
In order to read the data from the sharedPrefrences it is even more simplier
SharedPrefrences pref = mContext.getSharedPreferences(MODE_PRIVATE);
pref.getString("the key of the value");