Agam
Agam

Reputation: 31

Store json data sharedpreference and not overwrite

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<>();
                    }
            }

Upvotes: 0

Views: 116

Answers (1)

Lenoarod
Lenoarod

Reputation: 3620

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.

Upvotes: 1

Related Questions