I want to save and append data in shared preferences and display each data in listview , but it seems my code not works well. I'm new in android and I've already tried my best below , any help much appreciated
public class MainActivity extends AppCompatActivity {
public static final String PREFS_KEY = "notes";
ArrayList<CharSequence> list_items = new ArrayList<>();
ArrayAdapter arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StringBuilder stringBuilder = new StringBuilder();
saveNote();
ListView list = (ListView)findViewById(R.id.listview);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list_items);
list.setAdapter(arrayAdapter);
ArrayList<String> noteList = new ArrayList<>(getNotes());
for(int i = 0; i < noteList.size(); i++)
stringBuilder.append("\n" + noteList.get(i));
list_items.add(stringBuilder.toString());
arrayAdapter.notifyDataSetChanged();
}
public Set<String> getNotes() {
SharedPreferences settings = getApplicationContext().getSharedPreferences("notes", Context.MODE_PRIVATE);
// Get notes
Set<String> notes = settings.getStringSet(PREFS_KEY, new HashSet<String>());
return notes;
}
public void saveNote() {
String text = "New messages";
SharedPreferences settings = getApplicationContext().getSharedPreferences("notes", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
// Get existing notes
Set<String> notes = getNotes();
// Add new note to existing notes
notes.add(text);
// Store notes to SharedPreferences
editor.putStringSet(PREFS_KEY, notes);
editor.apply();
}
}