将SharedPreferences添加到Recycler适配器中的项目

时间:2015-08-06 08:50:47

标签: android sharedpreferences android-recyclerview

我希望能够检查其他活动是否检查了RecyclerView中的项目并且不知道如何操作。 我尝试使用SharedPreferences,但只获得一个空对象引用。

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
        at com.icedex.lolmon.testapp.firststart.FirstStartRecyclerAdapter$ViewHolder.<init>(FirstStartRecyclerAdapter.java:63)
        at com.icedex.lolmon.testapp.firststart.FirstStartRecyclerAdapter.onCreateViewHolder(FirstStartRecyclerAdapter.java:35)
        at com.icedex.lolmon.testapp.firststart.FirstStartRecyclerAdapter.onCreateViewHolder(FirstStartRecyclerAdapter.java:18)
        at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:5116)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4416)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4326)
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1955)
        at android.support.v7.widget.GridLayoutManager.layoutChunk(GridLayoutManager.java:437)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1327)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:556)
        at android.support.v7.widget.GridLayoutManager.onLayoutChildren(GridLayoutManager.java:171)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2713)
        at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3011)
        at android.view.View.layout(View.java:15671)
        at android.view.ViewGroup.layout(ViewGroup.java:5038)
        at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1626)
        at android.view.View.layout(View.java:15671)
        at android.view.ViewGroup.layout(ViewGroup.java:5038)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
        at android.view.View.layout(View.java:15671)
        at android.view.ViewGroup.layout(ViewGroup.java:5038)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
        at android.view.View.layout(View.java:15671)
        at android.view.ViewGroup.layout(ViewGroup.java:5038)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
        at android.view.View.layout(View.java:15671)
        at android.view.ViewGroup.layout(ViewGroup.java:5038)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2086)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1843)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
        at android.view.Choreographer.doCallbacks(Choreographer.java:580)
        at android.view.Choreographer.doFrame(Choreographer.java:550)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

这是我的代码:

public class FirstStartRecyclerAdapter extends RecyclerView.Adapter<FirstStartRecyclerAdapter.ViewHolder> {

public static final String TAG = "FSRecyclerAdapter";
public ArrayList<Card> cards;
public Context context;

public SharedPreferences sharedPref;

public boolean checkMusic = false;

public FirstStartRecyclerAdapter(Context context, ArrayList<Card> cards) {
    this.cards = cards;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);

    return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(FirstStartRecyclerAdapter.ViewHolder holder, int position) {

    Card card = cards.get(position);
    holder.card_tv.setText(card.cardName);
    holder.card_iv.setImageResource(card.getDrawable());
    holder.card_iv2.setImageResource(card.getDrawable2());
}

public int getItemCount() {
        return cards.size();
}

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public ImageView card_iv;
    public ImageView card_iv2;
    public TextView card_tv;

    public ViewHolder(View itemView) {
        super(itemView);
        card_tv = (TextView) itemView.findViewById(R.id.card_tv);
        card_iv = (ImageView) itemView.findViewById(R.id.card_iv);
        card_iv2 = (ImageView) itemView.findViewById(R.id.card_iv2);

        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int position = getLayoutPosition();
        Log.d(TAG, "clicked position:" + position);
        long postId = cards.get(position).getId();

        sharedPref = context.getSharedPreferences("myPref", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPref.edit();

        edit.putBoolean("checkWear", false);
        edit.apply();

        if (postId == 1) {

            if (sharedPref.getBoolean("checkWear", true)) {
                card_iv2.setImageResource(R.drawable.checkbox_blank_circle_outline);
                edit.putBoolean("checkWear", false);
                edit.apply();
            } else {
                card_iv2.setImageResource(R.drawable.checkbox_marked_circle);
                edit.putBoolean("checkWear", true);
                edit.apply();
            }
        }

        if (postId == 2) {

            if (checkMusic) {
                card_iv2.setImageResource(R.drawable.checkbox_blank_circle_outline);
                checkMusic = false;
            } else {
                card_iv2.setImageResource(R.drawable.checkbox_marked_circle);
                checkMusic = true;
            }
         }
      }
   }
}

我将不胜感激。

2 个答案:

答案 0 :(得分:1)

Nullpointer对我来说很奇怪......无论如何,这是另一种方法:

创建一个持有状态的静态类

final class State{  
  static boolean somethingIsChecked = false;  

  static boolean isSomethingChecked(){  
    return somethingIsChecked;  
  }  

  static void setSomethingIsChecked(boolean isChecked){  
    somethingIsChecked = isChecked;  
  }
}

然后在ViewHolders中调用onClick

State.setSomethingIsChecked(somevalue);

其他活动现在可以致电

State.isSomethingClicked();

获取值

请注意,Sharedpreferences和静态类都不能处理指向同一变量的多个实例,因此您应该在App结构中确保这些实例始终是singleInstance。

答案 1 :(得分:0)

这就是我所做的。 (如果您不能在SharedPreferences中访问类“ context”) 1.通过“ Context mConext”创建适配器类的上下文;或“私有WeakReference mContext”; 2.在需要在SharedPrefernce内部使用上下文的任何地方,都可以使用“ this.mContext.get()”来代替“ mContext”。喜欢 SharedPreferences首选项= this.mContext.get()。getSharedPreferences(MY_PREFERENCE_NAME,Context.MODE_PRIVATE);

我尝试了许多其他解决方案,但找不到东西。