Android Wear Projects
上QQ阅读APP看书,第一时间看更新

Fetching all the saved notes from SharedPreference

Fetching all the notes for this List type method needs a Context and then the SharedPreference reference using the PreferenceManager class. Then, we will create an instance of a List of notes for adding the notes after fetching it. We use the Map type for looping through the saved data inside SharedPreference. We will add all the data to the list inside the loop; it returns the noteList: 

public static List<Note> getAllNotes(Context context) {
    SharedPreferences sharedPreferences = 
    PreferenceManager.getDefaultSharedPreferences(context);
    List<Note> noteList = new ArrayList<>();
    Map<String, ?> key = sharedPreferences.getAll();
    for (Map.Entry<String, ?> entry : key.entrySet()) {
        String savedValue = (String) entry.getValue();

        if (savedValue != null) {
            Note note = new Note(entry.getKey(), savedValue);
            noteList.add(note);
        }
    }
    return noteList;
}