官术网_书友最值得收藏!

Removing notes from SharedPreference

To remove the data from SharedPreference, we need the key for the particular data item that we already set as the note ID. To remove the note, we need to pass the ID of the note and context. Using the SharedPreference editor, we will be able to remove the data: 

public static void removeNote(String id, Context context) {
    if (id != null) {
        SharedPreferences sharedPreferences = 
PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.remove(id); editor.apply(); } }

The complete class looks as follows:

package com.ashok.packt.wear_note_1.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.ashok.packt.wear_note_1.model.Note;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by ashok.kumar on 15/02/17.
 */

public class SharedPreferencesUtils {

    public static void saveNote(Note note, Context context) {
        if (note != null) {
            SharedPreferences sharedPreferences =   
            PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor editor = 
            sharedPreferences.edit();
            editor.putString(note.getId(), note.getNotes());
            editor.apply();
        }
    }


    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;
    }

    public static void removeNote(String id, Context context) {
        if (id != null) {
            SharedPreferences sharedPreferences = 
            PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor editor = 
            sharedPreferences.edit();
            editor.remove(id);
            editor.apply();
        }
    }
}
主站蜘蛛池模板: 慈溪市| 清苑县| 临夏市| 桑日县| 嘉定区| 承德县| 菏泽市| 青州市| 曲松县| 芷江| 连平县| 和静县| 平阳县| 洛隆县| 台湾省| 牙克石市| 芒康县| 临漳县| 邓州市| 永善县| 赤城县| 靖宇县| 太和县| 汝阳县| 西华县| 来安县| 太谷县| 弋阳县| 炎陵县| 潼关县| 隆尧县| 班戈县| 通山县| 青州市| 五寨县| 贵德县| 镇巴县| 信宜市| 江都市| 伊金霍洛旗| 广南县|