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

  • Android Wear Projects
  • Ashok Kumar S
  • 215字
  • 2021-07-15 17:17:57

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();
        }
    }
}
主站蜘蛛池模板: 丰都县| 外汇| 鄯善县| 平度市| 罗平县| 景泰县| 商河县| 合肥市| 库尔勒市| 无极县| 余姚市| 博乐市| 灌云县| 银川市| 仁怀市| 镇赉县| 女性| 揭东县| 武乡县| 紫云| 阆中市| 驻马店市| 沭阳县| 汝城县| 疏附县| 益阳市| 那坡县| 蓝山县| 从化市| 广昌县| 浦江县| 宜黄县| 临邑县| 龙川县| 章丘市| 三河市| 平武县| 松原市| 商河县| 马尔康县| 澜沧|