I'm having doubt and a problem I tried to solve with this Note App I found on Google, which is pretty simple, so I (a beginner) went to try few things on it. Everytime I save few notes, close app, restart app, it reorganizes the notes alphabetically, which I don't want. I know that Set and ArrayList are different in the sense a Set won't repeat elements, but ArrayList will. Also Set can't guarantee the order when called.
The question is: how is a good way to solve this instrinsecally sorting problem?
I've tried to switch what's HashSet to ArrayList, but the method putStringSet requires a Set in its parameters, which ArrayList isn't.
The following code works (doesn't crash or any other problem) but doesn't work as I want.
I have this part code in the MainActivity
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.tanay.thunderbird.deathnote", Context.MODE_PRIVATE);
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);
// a lot of other things here
if (set == null) {
notes.add("Example Note");
} else {
notes = new ArrayList<>(set); // to bring all the already stored data in the set to the notes ArrayList
}
On NoteEditorActivity I have
Intent intent = getIntent();
noteID = intent.getIntExtra("noteID", -1);
if (noteID != -1) {
editText.setText(MainActivity.notes.get(noteID));
} else {
MainActivity.notes.add(""); // as initially, the note is empty
noteID = MainActivity.notes.size() - 1;
MainActivity.arrayAdapter.notifyDataSetChanged();
}
//other things here
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
MainActivity.notes.set(noteID, String.valueOf(s));
MainActivity.arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.tanay.thunderbird.deathnote", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet<>(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}