我正在尝试从列表中向SharedPreferences添加值,这个想法是当用户点击按钮时列表项被添加到收藏夹页面,但是我无法这样做,我相信问题是因为我正在使用自定义ListViewAdapter,这个listview允许我向左滑动列表项,以便它显示按钮。 Like so 我不能让SharedPreferences在这个类中工作,这就是我所拥有的:
public class ListViewAdapter extends BaseSwipeAdapter {
ArrayList<HashMap<String, String>> array = TodasAsCategorias.getListaCategorias();
String Designacao, K_PRODUTO;
public static final String favoritos = "favoritos";
private Context mContext;
public ListViewAdapter(Context mContext) {
this.mContext = mContext;
}
@Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
@Override
public View generateView(final int position, ViewGroup parent) {
final View v = LayoutInflater.from(mContext).inflate(R.layout.list_item_cat, null);
SwipeLayout swipeLayout = (SwipeLayout) v.findViewById(getSwipeLayoutResourceId(position));
v.findViewById(R.id.imgBtnFav).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Designacao = (array.get(position)).get("Designacao");
K_PRODUTO = (array.get(position)).get("K_PRODUTO");
Toast.makeText(mContext, "Adicionado aos favoritos", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getSharedPreferences(favoritos, MODE_PRIVATE).edit();
editor.putString("Designacao", Designacao);
editor.apply();
}
});
return v;
}
/*....*/
}
它一直给我同样的错误,无法解析方法'getSharedPreferences(java.lang.String,?)'并且无法解析符号'MODE_PRIVATE'
这里真的需要帮助,在网上找不到任何帮助我的东西:/
答案 0 :(得分:1)
getSharedPreferences()需要访问上下文。
mContext.getSharedPreferences
尝试
SharedPreferences.Editor editor = mContext.getSharedPreferences(favoritos, MODE_PRIVATE).edit();
答案 1 :(得分:1)
尝试
SharedPreferences.Editor editor = mContext.getSharedPreferences(favoritos, Context.MODE_PRIVATE).edit();