android - 共享首选项删除不起作用

标签 android sharedpreferences android-context

希望有人能帮忙,连续处理这个问题三天了,不走运,掉头发了!!。 我可以从共享首选项中保存和加载对象,但我不能不删除它们,它不起作用。我没有收到任何错误

它通常从共享首选项加载对象并向其添加对象,但是当我调用删除方法时,它会重新加载数组列表并提取与丢失位置的原始负载不同的新对象数组。不确定是否有意义;希望有人能帮忙。

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

    }
   }

}

最佳答案

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

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

我认为这将从共享首选项中删除对象

关于android - 共享首选项删除不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27407718/

相关文章:

android - android有多少种context,用什么比较好

android - 如何从 Android 中的对话框启动 Activity

java - Android Studio - 将目标兼容性设置为 JDK 1.8 后 Gradle 构建失败

Android Kotlin - 无法解析 Firebase

android - React Native PanResponder 限制X位置

java - SharedPreferences 问题 - 丢失上次保存的值

Android - 在设备上存储图像?

java - Android Java - 共享首选项编辑器问题

android - 获取应用程序上下文以显示图形组件

Android:在 Activity 之间传递 HashMap