-1

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();
            }
Mark Jeronimus
  • 9,278
  • 3
  • 37
  • 50
  • Try the solution here: https://stackoverflow.com/questions/7965290/put-and-get-string-array-from-shared-preferences – Lee3 Dec 11 '20 at 10:11

1 Answers1

0

If you would like to keep the order of the notes, Array or List is truly the better choice than using Set.

To store this into SharedPreferences, you can refer to Put and get String array from shared preferences

This question has answers explaining the followings:

  1. Jsonify the list and parse it back.
  2. Concatenate all the Strings with delimiter and split it back.
Hyun I Kim
  • 589
  • 1
  • 3
  • 14