Search code examples
javaandroidandroid-recyclerviewsharedpreferences

How to get SharedPreferences float value in RecyclerView Adapter?


I am using this SharedPref Class for saving and retrieving value from it. Here I created setTextSize & getTextSize methods.

SharedPref.java


public class SharedPref {
            SharedPreferences mySharedPref;
            float aFloat = 18.0f;

    // this method will save the text size
    public void setTextSize(float tSize) {
        SharedPreferences.Editor editor = mySharedPref.edit();
        editor.putFloat("TextSize",tSize);
        editor.apply();
    }
    
    // this method will get the text size
    public float getTextSize (){
        return mySharedPref.getFloat("TextSize",aFloat);
    }
}

Now I want to call getTextSize method in RecyclerView Adapter for set text size.

NameAdapter.java

public class NameAdapter extends RecyclerView.Adapter<NameAdapter.NameViewHolder> implements Filterable {

    Context context;
    List<NameModel> nameItemList;

    public NameAdapter(@NonNull Context context, List<NameModel> nameItemList) {
        this.context = context;
        this.nameItemList = nameItemList;
    }

    @NonNull
    @Override
    public NameViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.name_item,parent, false );
        return new NameViewHolder(view);
    }

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

        holder.name.setText(nameItemList.get(position).getName());
        holder.meaning.setText(nameItemList.get(position).getMeaning());

        // here I want to use setTextSize method from SharedPref
        holder.name.setTextSize(getTextSize);
    }

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

      public class NameViewHolder extends RecyclerView.ViewHolder{

        TextView name,meaning;

        public NameViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.tvName);
            meaning = (TextView) itemView.findViewById(R.id.tvMeaning);

        }
    }

}

Please help. Thanks in advance.


Solution

    • You can pass values in constructor like this

        Context context;
        List<NameModel> nameItemList;
        Float prepsValue;
      
        public NameAdapter(@NonNull Context context, List<NameModel> nameItemList,Float prepsValue) {
            this.context = context;
            this.nameItemList = nameItemList;
            this.prepsValue =prepsValue;
        }