Search code examples
androidandroid-recyclerviewadapter

How can I save button state in recyclerview item


Hello I have an horizontal recyclerview which contains some products, where in the plus button I add the products to shopping cart and after product is added the icon changes. I did this, but my problem is to save the state of this button, because when I navigate between fragmets/activities and when app starts button remains unchanged. Here what I have:

enter image description here

The code in my adapter is:

@Override
    public void onBindViewHolder(@NonNull ArtikujtViewHolder holder, int position) {
        final Artikujt mArtikull = artikujt.get(position);

        String mArtikullName = mArtikull.getEmertimet();
        holder.artikullName.setText(mArtikullName);
        String mArtikullCmimi = mArtikull.getCmimi().toString();
        holder.artikullCmimi.setText(mArtikullCmimi+" Leke");

        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(mContext, ProductDetailsActivity.class);
            intent.putExtra("positon", artikujt.get(position));
            intent.putExtra("mArtikullName", mArtikullName);
            intent.putExtra("mArtikullCmimi", mArtikullCmimi);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        });

        SharedPreferences preferences = mContext
                .getSharedPreferences(ITEMS_PREF, MODE_PRIVATE);
        SharedPreferences.Editor mEditor = preferences.edit();

        // using shared preferences to save the state
        if (preferences.contains(ITEMS_PREF)) {
            holder.addItems.setCompoundDrawablesWithIntrinsicBounds(0, 0,
                    R.drawable.ic_check_black, 0);
            holder.addItems.setEnabled(false);
        } else {

        }

        holder.addItems.setOnClickListener(v -> {
            Gson gson = new Gson();
            String json = preferences.getString("artikujtShporta", "");
            ArrayList<Artikujt> artikullObject = gson
                    .fromJson(json, new TypeToken<ArrayList<Artikujt>>(){}.getType());
            if (artikullObject != null) {
                artikullObject.add(mArtikull);
                String jsonString = gson.toJson(artikullObject);
                mEditor.putString("artikujtShporta", jsonString);
                mEditor.apply();
            } else {
                ArrayList<Artikujt> arrayArtikuj = new ArrayList<>();
                arrayArtikuj.add(mArtikull);
                Type listOfTestObject = new TypeToken<ArrayList<Artikujt>>() {}.getType();
                String s = gson.toJson(arrayArtikuj, listOfTestObject);
                mEditor.putString("artikujtShporta", s);
                mEditor.apply();
            }

             holder.addItems.setCompoundDrawablesWithIntrinsicBounds(0, 0,
              R.drawable.ic_check_black, 0);

            //======================================================================================
            // Display a toast message
            final Toast toast = Toast.makeText(mContext, R.string.shtuar_ne_shporte, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
            toast.show();
            Handler handler = new Handler();
            handler.postDelayed(toast::cancel, 1000);
            //======================================================================================

            assert artikullObject != null;
            count_key = artikullObject.size();

            String cartCount = String.valueOf(count_key);
            Intent my_intent = new Intent("msg");
            my_intent.putExtra("cart_count", cartCount);
            LocalBroadcastManager.getInstance(mContext).sendBroadcast(my_intent);

            v.setEnabled(false);
        });

    }

I searched a lot about it and the solution could be using shared preferences to save the state, with sharedprerences.contains(preferences_id) but I'm confused here. Does anyone have any suggestion how can I achieve this or which could be possible solutions. Thanks in advance.


Solution

  • I am assuming that you want to keep the button as it was after clicking it:

    If that is your problem, yes we will use shared prefrences:

    @Override
    public void onBindViewHolder(@NonNull ArtikujtViewHolder holder, int position) {
    
    //the item
    final Artikujt mArtikull = artikujt.get(position);
    
    ..........
    ..........
    
    //read the prefrences
    SharedPreferences pref = getSharedPreferences("Button", MODE_PRIVATE);
    String state = pref.getString(String.valueOf(position)+"pressed", "no");
    
    if(state.equals("yes")){
    
    //the button must be pressed, make it pressed (check mark icon)
    
    //change the icon
    holder.addItems.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_check_black, 0);
    
    holder.addItems.setEnabled(false);
    
    }else{
    //the button must not be pressed, make it not pressed (default add icon)
    
    //change the icon
    holder.addItems.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_add_icon, 0);
    
    holder.addItems.setEnabled(true);
    }
    
    
    //after clicking the add icon
    
    holder.addItems.setOnClickListener(v -> {
    
    //save to preferences
    SharedPreferences.Editor editor = getSharedPreferences("Button", MODE_PRIVATE).edit();
    editor.putString(String.valueOf(position)+ "pressed", "yes");
    editor.apply();
    
    
    //change the icon
    holder.addItems.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_check_black, 0);
                //======================================================================================
    // Display a toast message
    final Toast toast = Toast.makeText(mContext, R.string.shtuar_ne_shporte, Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
    toast.show();
    Handler handler = new Handler();
    handler.postDelayed(toast::cancel, 1000);
                //======================================================================================
    
    assert artikullObject != null;
    count_key = artikullObject.size();
    
    String cartCount = String.valueOf(count_key);
    Intent my_intent = new Intent("msg");
    my_intent.putExtra("cart_count", cartCount);
    LocalBroadcastManager.getInstance(mContext).sendBroadcast(my_intent);
    
    v.setEnabled(false);
    
    });
    
    
    }