Search code examples
androidsharedpreferencesnavigation-drawernavigationview

Is there a way to remove an item from sharedpreferences?


I have a navigation view in which i add items programmatically and i save them-to restore later-in sharedpreferences.

My question is: How to remove a specific item from the sharedpreferences when i press long click on a specific item from navigationview?

This is my code:

    private void saveData() {
    SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_LIST_KEY, MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    Gson gson = new Gson();
    String json = gson.toJson(navItems);
    editor.putString(SHARED_PREF_LIST_KEY_ITEM, json);
    editor.apply();
}

    private void loadData() {
    SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_LIST_KEY, MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sharedPreferences.getString(SHARED_PREF_LIST_KEY_ITEM, null);
    Type type = new TypeToken<ArrayList<NavItem>>() {
    }.getType();
    navItems = gson.fromJson(json, type);
    if (navItems == null) {
        navItems = new ArrayList<>();
    }
}

public class NavItem {
private String name;

public NavItem(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

}


Solution

  • You can create a new method for removing the specific item and after removing the item save the updated list back to shared preferences.

    Look at the example below:

    private void deleteData(NavItem item) {
        SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_LIST_KEY, MODE_PRIVATE);
        Gson gson = new Gson();
        String json = sharedPreferences.getString(SHARED_PREF_LIST_KEY_ITEM, null);
        Type type = new TypeToken<ArrayList<NavItem>>() {
    }.getType();
        navItems = gson.fromJson(json, type);
        if (navItems! = null) {
            navItems.remove(item);
            saveData() ;// save the updated list to shared preferences 
        }
    }
    

    Hopw it helps.