Search code examples
javaandroidlistviewsharedpreferences

How to remove a specific item from ListView and SharedPreferences?


I save History items (words) to SharedPreferences, and History is well loaded to view in a ListView. I then use these code lines to delete a specific item from the ListView:

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()) {
        case R.id.edit:
            editNote(info.id);
            return true;
        case R.id.delete:
            String content = (String) mLSTHistory.getItemAtPosition(info.position);
               aptList.remove(content);
               aptList.notifyDataSetChanged();
            deleteNote(info.id);
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}
private void deleteNote(long id) {
    // TODO Auto-generated method stub
    if (prefs.getBoolean("saveHistory", true) && mWordHistory != null && mWordHistory.size() >= 1)

    prefs =   PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    StringBuilder sbHistory = new StringBuilder();
    for (String item : mWordHistory)
    {
        sbHistory.append(item);
        sbHistory.append(",");

    String strHistory = sbHistory.substring(0, sbHistory.length()-1);
    SharedPreferences.Editor editor = prefs.edit();
    //editor.remove(content);
    editor.putString("history", strHistory);
    editor.commit();
    }
}
private void editNote(long id) {
    // TODO Auto-generated method stub

}

The selected item is definetely removed from the ListView, but it is not deleted from SharedPreferences in which it is saved. Consequently, when the Listview is re-loaded, the item is still there.

My question is: how can I code to remove the selected item from SharePreferences as well? I mean how can I do to remove the selected item from both ListView and SharedPreferences?

It would be great if you could provide instructions based on my code as I'm quite new with Android. Thank you very much.


Solution

  • To clear shared prefrences, Use

    editor.clear();
    editor.commit();
    

    Also if, i have got your question correctly. To check if a value is stored in shared preferences, do this

    SharedPreferences mySharedPrefs = getSharedPreferences("MyPreferences", 0);
                    if(mySharedPrefs.contains("theKey")) {
    SharedPreferences.Editor editor = settings.edit();
                    editor.remove("thekey");
                    editor.commit();
    }