【问题标题】:Android: how do I set a SharedPreferences counter to a RecyclerView TextView?Android:如何将 SharedPreferences 计数器设置为 RecyclerView TextView?
【发布时间】:2016-05-04 05:26:34
【问题描述】:

我有一个 Activity,其中单击按钮将一组用户输入数据保存到 SQLite 数据库,然后在 RecyclerView 列表中填充 CardView。我想创建一个计数器,该计数器以默认值零开始,每次单击“保存”按钮时递增 +1(创建一个新的 CardView),然后将该计数器输出到 RecyclerView 列表中的 CardView 上。

我在 OnBindViewHolder 方法的 Adapter 文件中出现 Android Studio 错误,在它开始“holder...”的最后一行我如何从 Activity 获取 Context 到 Adapter 文件?我认为 getSharedPreferences() 允许全局上下文,而 getPreferences() 不起作用。

我通过单击按钮在 Activity 文件中使用 SharedPreferences 设置计数器:

public class Activity extends AppCompatActivity {
...
    public void onClickSave(View v) {
    ...
    int totalcount = 0;
    SharedPreferences sp = getSharedPreferences("Share_Prefs",Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putInt("int_key", ++totalcount);
    editor.apply();  

RecyclerView Adapter 文件有如下代码:

public class Adapter extends RecyclerView.Adapter<Adapter.ListViewHolder> {
    ....
    Context context;
    ....
    public Adapter(Context context, List<UserData> dbList) {
    this.context =  context;

    public class ListViewHolder extends RecyclerView.ViewHolder {

        TextView cardBlankTextNums; 

        public ListViewHolder(View itemView) {
        super(itemView);

        cardBlankTextNums = (TextView)itemView.findViewById(R.id.cardBlankTextNums);

        @Override
        public int getItemCount() {
            return dbList.size();
        }

    @Override
    public void onBindViewHolder(final ListViewHolder holder, final int position) {

    int totalcount = 0;

    holder.cardBlankTextNums.setText(dbList.get(position).getSharedPreferences.edit.getInt("int_key",totalcount));      

【问题讨论】:

  • dbList.get(position).getSharedPreferences...语法不正确
  • 对正确的语法有什么想法吗?
  • 我会在下面发布答案

标签: android sharedpreferences android-recyclerview


【解决方案1】:

getSharedPreferencesContext 上工作,并且由于您的适配器没有,因此无法解析名称,因此您需要以某种方式将上下文传递给您的适配器类。最好在构造函数中做:

public class Adapter extends RecyclerView.Adapter<Adapter.ListViewHolder> {

    private Context mContext;

    public Adapter (Context context)
    {
        mContext = context;
    }

    ...

public void onBindViewHolder(final ListViewHolder holder, final int position) {

    holder.cardBlankTextNums.setText(mContext.getSharedPreferences("Share_Prefs",Context.MODE_PRIVATE).getInt("int_key",totalcount));

当你想实例化一个新的适配器时,你需要传递上下文。例如,如果您正在参加您需要做的活动:

Adapter newAdapter = new Adapter(this);

如果你在一个片段中你需要做的:

Adapter newAdapter = new Adapter(getActivity());

【讨论】:

  • 所以setText不需要使用“dbList.get(position)...”的CardView位置?
  • @AJW 个人我不确定您使用的是什么逻辑,但是无论您的视图位置如何,getSharedPreferences 都会返回一个固定数字
  • 我确实传递了上下文,但我忘了包括。我将编辑上面的代码以显示。
  • @AJW 你需要调用 context.getSharedPreferences(...)
  • 好的,我更新了持有者以包含您建议的上下文代码。除了“总数”之外,所有看起来都是商品。我假设我需要为此设置一个 int 变量?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 2022-09-27
相关资源
最近更新 更多