如何在RecyclerView.Adapter中使用共享偏好设置?

3

如何在RecyclerView.Adapter中使用共享偏好设置?我已经在RecyclerView.Adapter中使用了共享偏好设置的值,但是没有保存到共享偏好设置中。我应该在哪里使用共享偏好设置呢?是在RecyclerView.Adapter还是在活动中?

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

    private ImageLoader imageLoader;
    private Context context;
    private String gd;

    public static final String SHARED_PREF_NAME = "myloginapp";
    //We will use this to store the boolean in sharedpreference to track user is loggedin or not
    public static final String LOGGEDIN_SHARED_PREF = "loggedin";
    public static final String GROUPSNAME_SHARED_PREF = "groupname";

    public CardAdapter(Context context) {
        this.context = context;
    }

        //List of superHeroes
        List<Group> groups;

        public CardAdapter(List < Group > groups, Context context) {
            super();
            //Getting all the superheroes
            this.groups = groups;
            this.context = context;
        }

        @Override
        public ViewHolder onCreateViewHolder (ViewGroup parent,int viewType){
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.groups_list, parent, false);
            ViewHolder viewHolder = new ViewHolder(v);
            return viewHolder;
        }

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

            Group group1 = groups.get(position);

            imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
            imageLoader.get(group1.getPic(), ImageLoader.getImageListener(holder.imageView, R.drawable.ic_launcher, android.R.drawable.ic_dialog_alert));

            holder.imageView.setImageUrl(group1.getPic(), imageLoader);
            holder.groupname.setText(group1.getGname());//i want to store this value in shared preference..
            holder.groupinfo.setText(group1.getGinfo());
            gd = holder.groupname.getText().toString();//variable gd is storing any value.
            holder.add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, Viewgroup1.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }
            });

        }

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

        class ViewHolder extends RecyclerView.ViewHolder {
            public NetworkImageView imageView;
            public TextView groupname;
            public TextView groupinfo;
            public Button add;


            public ViewHolder(View itemView) {
                super(itemView);
                imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
                groupname = (TextView) itemView.findViewById(R.id.textViewName);
                groupinfo = (TextView) itemView.findViewById(R.id.textViewRank);
                add = (Button) itemView.findViewById(R.id.button7);
                //String gd = holder.groupname.getText().toString();

                SharedPreferences sharedPreferences1 = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);

                //Creating editor to store values to shared preferences
                SharedPreferences.Editor editor = sharedPreferences1.edit();

                //Adding values to editor
                editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
                editor.putString(GROUPSNAME_SHARED_PREF, gd);

            }
        }
    } 

Viewgroup.java

public class Viewgroup extends AppCompatActivity {

    //Creating a List of superheroes
    private List<Group> listSuperHeroes;
    private String vault;
    //Creating Views
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recycle);

        //Initializing Views
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        //Initializing our superheroes list
        listSuperHeroes = new ArrayList<>();
        SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);
        vault = sharedPreferences.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");
        //Calling method to get data
        getData();
    }

    //This method will get data from the web api
    private void getData(){
        //Showing a progress dialog
        final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);

        //Creating a json array request
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL+vault,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        //Dismissing progress dialog
                        loading.dismiss();

                        //calling method to parse json array
                        parseData(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        //Creating request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(jsonArrayRequest);
    }

    //This method will parse json data
    private void parseData(JSONArray array){
        for(int i = 0; i<array.length(); i++) {
            Group group1 = new Group();
            JSONObject json = null;
            try {
                json = array.getJSONObject(i);
                group1.setPic(json.getString(Config.TAG_IMAGE_URL));
                group1.setGname(json.getString(Config.TAG_NAME));
                group1.setGinfo(json.getString(Config.TAG_INFO));

            } catch (JSONException e) {
                e.printStackTrace();
            }
            listSuperHeroes.add(group1);
        }

        //Finally initializing our adapter
        adapter = new CardAdapter(listSuperHeroes, this);

        //Adding adapter to recyclerview
        recyclerView.setAdapter(adapter);


       /* recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                final Button add = (Button)  v.findViewById(R.id.button7);
                final TextView txtStatusChange = (TextView) v.findViewById(R.id.textViewName);
                //final TextView txtStatusChange1 = (TextView) v.findViewById(R.id.textView33);
                add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Intent intent = new Intent(Viewgroup.this, Viewgroup1.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        // Log.e(TAG_IMAGE_URL, "hello text " + txtStatusChange.getText().toString() + " TAG " + txtStatusChange.getTag().toString());
                        Toast.makeText(Viewgroup.this, txtStatusChange.getText().toString(), Toast.LENGTH_SHORT).show();
                    }
                });
                return false;
            }
        });*/
    }
}

2
在哪里调用 commitapply 方法以保存更改? - ρяσѕρєя K
哦,我的错...谢谢你找到了这个漏洞..我现在会尝试修复它的。 - sunil y
@prosper K.,为什么共享首选项没有更新呢?我已经在holder.add.setOnClickListener(new View.OnClickListener()中使用了共享首选项,但是值没有更新。 - sunil y
看一下我的回答,可能有助于解决问题。 - ρяσѕρєя K
这是我所做的。 (如果您无法在SharedPreferences中访问类“context”)
  1. 通过“Context mContext”或“private WeakReference <Context> mContext;”创建适配器类的上下文。
  2. 在需要在SharedPrefernce内使用上下文的任何地方,使用“this.mContext.get()”而不是给出“mContext”,例如 SharedPreferences preferences = this.mContext.get().getSharedPreferences(MY_PREFERENCE_NAME,Context.MODE_PRIVATE);
我尝试了很多其他解决方案,但找不到正确的方法。
- ABHIMANGAL MS
5个回答

3
您应该在代码中添加editor.commit()editor.apply()来将数据保存到Sharedpreferences。请在您的代码下方添加此代码。
//Adding values to editor
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(GROUPSNAME_SHARED_PREF, gd);
editor.apply();

为什么共享偏好没有更新..?我在 holder.add.setOnClickListener(new View.OnClickListener() ..中使用了共享偏好,但值没有更新.. - sunil y

2
为什么共享偏好值没有更新..?
在启动活动之前,使用按钮的onClick方法将值保存在Sharedpreferences中,如下所示:
...
gd = holder.groupname.getText().toString();
holder.add.setTag(gd);
...
     @Override
     public void onClick(View view) {
         String strValue=view.getTag().toString();
         ... save  strValue in Sharedpreferences
         ...
         editor.putString(GROUPSNAME_SHARED_PREF, strValue);
         editor.apply();
         // start new Activity..
      }
...

@prosper K..先生,如果您能帮助我,您能看到这个问题吗?问题链接 - sunil y

0

这是我所做的(如果您无法在SharedPreferences中访问类"上下文")

  1. 通过Context mContext;private WeakReference<Context> mContext; 创建一个适配器类的上下文
  2. 在需要使用SharedPreferences的地方,不要使用mContext,而是使用this.mContext.get(),例如: SharedPreferences preferences = this.mContext.get().getSharedPreferences(MY_PREFERENCE_NAME, Context.MODE_PRIVATE);

我尝试了很多其他解决方案,但没能找到正确的方法。


0

如果您在 onCreateViewHolder 视图持有器中使用此方法,请使用 itemView.getContext()。 获取数据 在使用 getSharedPreferences 之前,请先使用 itemView.getContext()。 保存也是一样的。

Sharedpreferences prefs = holder.itemView.getContext().getSharedPreferences("SHARED_PREFS", holder.itemView.getContext().MODE_PRIVATE); String Variable= holder.prefs.getString("yourkey", null);


0

它可以工作,只需添加this.mcontext.getContext而不是this.mContext.get()。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接