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"]
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();
}
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 {
Then format the string as our requirement before add the string to arraylist .
String allvalues = String.format("" + "%s," + "\"" + "%s\"", finalpreferenceValue, valueofeditText);
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();
}