Search code examples
javaandroidsharedpreferences

Adding the value of a text field and a saved value from SharedPreferences to an array


I have a text field and I want its value to be saved. Also, if the same text field had another value before, it should be saved too.

This is how I tried it:

ArrayList<String> listOfTexts = new ArrayList<>();

SharedPreferences mPrefs = getContext().getSharedPreferences("k-texts", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();

listOfTexts.add(Objects.requireNonNull(_customTextField.getText()).toString());
listOfTexts.add(mPrefs.getString("k-text", ""));

Gson gson = new Gson();
String json = gson.toJson(listOfTexts);
prefsEditor.putString("k-text", json);
prefsEditor.apply();

I have saved multiple values in that field. The values are: a, b, c and d

Well, in that case, json returns ["d","["c","[\"a\",\"\",\"b\",\"[\\\"a\\\",\\\"\\\"]\"]"]"] but what I want is ["a", "b", "c", "d"]

How can I get the result that I want?


Solution

  • in this case exits some conflicts in your logic . Instead using Gson use String.format .

    When you are adding a in your arraylist and saving to shared preference its giving perfect result [a] .

    Then you are trying to add b from edittext and [a] got from preference - result [b,[a]]. and when you trying to make it json its making too conflict .

    However , based on your requirement the result should be ["a", "b", "c", "d"]

    1. So when retrieve data from preference replace [] . After replaced it looks like "a" or "a", "b" or etc . We dont need [] from preference , we would get it from ArrayList .

      valuefromPrefrence = mPrefs.getString("k-text", null);
      try {
          finalpreferenceValue = valuefromPrefrence.replace("[", "").replace("]",    "");
      } catch (Exception e) {
       e.printStackTrace();
      }
      
    2. We can check saved data to skip duplicate data store .

      if (finalpreferenceValue != null && finalpreferenceValue.contains(valueofeditText)) {
               Toast.makeText(getApplicationContext(), "Data already exists", Toast.LENGTH_SHORT).show();
           } else {
      
    3. Then format the string as our requirement before add the string to arraylist .

      String allvalues = String.format("" + "%s," + "\"" + "%s\"", finalpreferenceValue, valueofeditText);
      
    4. Then add formated String and store the data . Thats it .

    So you may check -

            ArrayList<String> listOfTexts = new ArrayList<>();
    
        SharedPreferences mPrefs = getApplicationContext().getSharedPreferences("k-texts", Context.MODE_PRIVATE);
        SharedPreferences.Editor prefsEditor = mPrefs.edit();
    
    
        String valueofeditText = Objects.requireNonNull(_customTextField.getText()).toString();
        String valuefromPrefrence, finalpreferenceValue = null;
    
        valuefromPrefrence = mPrefs.getString("k-text", null);
        try {
            finalpreferenceValue = valuefromPrefrence.replace("[", "").replace("]", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (finalpreferenceValue != null && finalpreferenceValue.contains(valueofeditText)) {
            Toast.makeText(getApplicationContext(), "Data already exists", Toast.LENGTH_SHORT).show();
        } else {
    
            String allvalues = String.format("" + "%s," + "\"" + "%s\"", finalpreferenceValue, valueofeditText);
    
            //replace null, got from first time load   valuefromPrefrence = mPrefs.getString("k-text", "");
    
            String rallvalues = allvalues.replace("null,", "");
    
            listOfTexts.add(rallvalues);
    
            prefsEditor.putString("k-text", String.valueOf(listOfTexts));
            prefsEditor.apply();
        }