0

I'm adding views to a RecyclerView by clicking on a button, I want those views to be saved, preferably in SharedPrefrences how do we do this and do we need a json?

Here's the adapter:

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

    public List<String> items = new ArrayList<>();
    public Activity mcontext;

    public SubjectsAdapter(Activity context) {
        this.mcontext=context;
    }

    public void addItem(String name) {
        items.add(name);
        notifyItemInserted(items.size() - 1);
    }

    public void removeItem(int position) {
        items.remove(position);
        notifyItemRemoved(position);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.grid_item_button, parent, false);
        view.requestFocus();
        return new ViewHolder(view);
    }

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

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

    static int i = 100;
    static int h = 1000;
    public EditText EditName;

    class ViewHolder extends RecyclerView.ViewHolder{

        public Button GridButton;
        private TextView ClassName;
        public SharedPreferences prefs;

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

            GridButton = (Button) itemView.findViewById(R.id.grid_button);
            EditName = (EditText) itemView.findViewById(R.id.editName);
            ClassName = (TextView) itemView.findViewById(R.id.ClassName);
            prefs = mcontext.getPreferences(Context.MODE_PRIVATE);

            GridButton.setId(++i);
            GridButton.setText(prefs.getString("key", i + ""));

            EditName.requestFocus();
        }
    }
}

I'm adding views from the activity like this adapter.addItem("something");

John Sardinha
  • 3,566
  • 6
  • 25
  • 55

1 Answers1

0

You cant' store views in the SharedPreference, but you can store the value of the textview.

pref = getSharedPreferences(prefName, Context.MODE_PRIVATE);
SharedPreferences.Editor ed;
ed = pref.edit();
ed.putString(prefKey2, textView.getText().toString()).commit();

Then you can set the stored value to the textview

textView.setText(pref.getString(prefKey2, ""));
MrRobot9
  • 2,402
  • 4
  • 31
  • 68