Sharedpreferences 删除不起作用

Posted

技术标签:

【中文标题】Sharedpreferences 删除不起作用【英文标题】:Sharedpreferences remove not working 【发布时间】:2015-02-09 01:02:50 【问题描述】:

希望有人可以提供帮助,连续处理 3 天而不是运气,失去了我的头发!!。 我可以从共享首选项中保存和加载对象,但我不能不删除它们,它不起作用。我没有错误

它通常会从 sharedpreferences 加载并将对象添加到 sharedpreferences 中,但是当我调用 remove 方法时,它会重新加载数组列表并拉出一个与原始加载不同的新对象数组,从而丢失位置。不确定是否有意义;希望有人能帮忙。

public class FavFragment extends Fragment 
Context context;
private ListView lv;
private ArrayList<VocabCatModel> vocabCatList;
FavVocabAdapter adapter;
SharedPreference sharedPreference;

public static FavFragment newInstance() 
    FavFragment fragment = new FavFragment();
    return fragment;


public FavFragment() 



@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    sharedPreference=new SharedPreference(getActivity());
    System.out.println("Loading Favorites new SHaredpreference object");
    try 
        vocabCatList = sharedPreference.loadFavorites(getActivity());
        System.out.println("Current Favs: " + vocabCatList);
        System.out.println("Current context after loading first time:" + getActivity());
     catch (NullPointerException e)
        e.printStackTrace();
    


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 
    View rootView = inflater.inflate(R.layout.vocab_search, container, false);
    lv = (ListView) rootView.findViewById(R.id.list_view);
    return rootView;


@Override
public void onResume() 
    super.onResume();
    Log.e("onResume", "onResume Called");
    if(vocabCatList != null ) 
        try 
            Log.e("adapter", "new adapter and setting up to listview");
            adapter = new FavVocabAdapter(getActivity(), vocabCatList);
            lv.setAdapter(adapter);
            System.out.println("Favs after lv.setadapter: "+ vocabCatList);
         catch (NullPointerException e) 
            e.printStackTrace();
        
        adapter.notifyDataSetChanged();
    
    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3)
            sharedPreference.removeFavorite(getActivity(), vocabCatList.get(position));
            adapter.notifyDataSetChanged();
            Toast.makeText(arg0.getContext(), vocabCatList.get(position) + "removed",              Toast.LENGTH_SHORT)
                    .show();
            vocabCatList.remove(vocabCatList.get(position));
            return true;
        
    );



public class FavVocabAdapter extends BaseAdapter 
    Context context;
    ArrayList<VocabCatModel> vocabCatList;
    public FavVocabAdapter(Context context, ArrayList<VocabCatModel> vocabCatList)
        this.context = context;
        this.vocabCatList = vocabCatList;
    
    public int getCount()return vocabCatList.size();
    public Object getItem(int position)return vocabCatList.get(position);
    public long getItemId(int position)return position;

    private class ViewHolder 
        TextView tvName,tvTranslation;
        ImageView ivImage;
    

    @Override
    public View getView(final int position, View convertView, ViewGroup parent)
        final ViewHolder holder;
        //convertView = null;
        LayoutInflater mInflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        if (convertView == null)
            convertView = mInflater.inflate(R.layout.categorylistviewitem, parent, false);
            holder = new ViewHolder();
            holder.tvName = (TextView)convertView.findViewById(R.id.itemTextView);
            holder.tvTranslation = (TextView)convertView.findViewById(R.id.translationTextView);
            holder.ivImage = (ImageView)convertView.findViewById(R.id.itemImage);
            convertView.setTag(holder);

        else 
            holder = (ViewHolder) convertView.getTag();
        

        holder.tvName.setText(vocabCatList.get(position).getName());
        holder.tvTranslation.setText(vocabCatList.get(position).getTranslation());
        holder.ivImage.setImageResource(R.drawable.ic_favorite);
        holder.ivImage.setOnClickListener(new View.OnClickListener()

            @Override
            public void onClick(View view)
                    sharedPreference.removeFavorite(context, vocabCatList.get(position));
                    vocabCatList.remove(vocabCatList.get(position));
                    holder.ivImage.setImageResource(R.drawable.directions);
                    notifyDataSetChanged();
            
        );
        return convertView;
    




/////////////////////我正在使用的共享偏好类

public class SharedPreference 
private Context context;
public static final String PREFS_NAME = "VOCAB_APP";
public static final String FAVORITES = "Favorite";

public  SharedPreference(Context context)

  super();



public void storeFavorites(Context context, List<VocabCatModel> favorites)
    SharedPreferences settings;
    Editor editor;

    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    editor = settings.edit();

    Gson gson = new Gson();
    String jsonFavorites = gson.toJson(favorites);
    System.out.println(favorites);

    editor.putString(FAVORITES, jsonFavorites);

    System.out.println("commit()");
    editor.apply();



public ArrayList<VocabCatModel> loadFavorites(Context context) 
    SharedPreferences settings;
    List<VocabCatModel> favorites;

    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    if (settings.contains(FAVORITES)) 
        String jsonFavorites = settings.getString(FAVORITES, null);
        Gson gson = new Gson();
        System.out.println("loading favorites");
        VocabCatModel[] favoriteItems = gson.fromJson(jsonFavorites,VocabCatModel[].class);
        favorites = Arrays.asList(favoriteItems);
        favorites = new ArrayList<>(favorites);
     else
        return null;

    return (ArrayList<VocabCatModel>) favorites;

public void addFavorite(Context context, VocabCatModel vocabCatModel) 
    List<VocabCatModel> favorites = loadFavorites(context);
    if (favorites == null)
        favorites = new ArrayList<>();
    favorites.add(vocabCatModel);
    storeFavorites(context, favorites);


public void removeFavorite(Context context, VocabCatModel vocabCatModel) 
    ArrayList<VocabCatModel> favorites = loadFavorites(context);
    System.out.println("Removing favorite");
    System.out.println("new favs" + favorites);
    if (favorites != null) 
        System.out.println("object from click" + vocabCatModel);
        favorites.remove(vocabCatModel);
        System.out.println(context);
        storeFavorites(context, favorites);

    
   


【问题讨论】:

您是否按预期进行了系统打印调用? favorites.remove(vocabCatModel); 真正起作用的可能性很小。测试返回值。 @zgc7009 是的,我正在按预期进行系统打印调用.. @njk2 我试试看 【参考方案1】:

如果您需要删除或移除您之前放置的对象或项目 试试这个:

SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
editor = settings.edit();
try
    System.out.println("PREFS_NAME:"+settings.getString(PREFS_NAME,""));
    editor.remove(PREFS_NAME);
    editor.commit();
catch(Exception e)
    System.out.println("Cart Error");

我认为这会从 sharedprederences 中删除对象

【讨论】:

以上是关于Sharedpreferences 删除不起作用的主要内容,如果未能解决你的问题,请参考以下文章

Android:将 ArrayList 保存到 SharedPreferences,但加载它不起作用

在 Android 中备份 SharedPreferences?

孤儿删除不起作用

TableView 滑动删除不起作用

为啥使用 sed 删除不起作用?

删除()函数不起作用