0

The code below saves the current text of the TextView when the favourite button is clicked and the button Image changes to Fav_Checked when I click again the favourite button is unchecked and the text in array is removed but the issue is when I scroll down the ListView updates and the favourite buttons are unchecked. kindly help.

public class MainActivity extends AppCompatActivity {

//     ArrayList<String> names = new ArrayList<>();
    private ArrayList<String> names;
    int x = names.size();
//    private boolean[x] favorites;
    private SharedPreferences sharedPreferences;

    Context context = this;
    MediaPlayer mPlayer;
    Boolean isPlay = true;
    ImageView playPauseGlobelBtn;
    int maxVolume,resID,position;
    String fname;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         ListView listView=(ListView)findViewById(R.id.listView);
        mPlayer = MediaPlayer.create(context, R.raw.asdf);
        CustomAdapter customAdapter=new CustomAdapter();
        listView.setAdapter(customAdapter);

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        String favoriteItems = sharedPreferences.getString("FAVORITE_ITEMS", "");

        if(favoriteItems.isEmpty()) {
            names = new ArrayList<>();
        }
        else {
            names = new ArrayList<>(Arrays.asList(favoriteItems.split(",")));
        }
    }
    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        view = getLayoutInflater().inflate(R.layout.customlayout, null);
         final TextView textView_name = (TextView) 
        view.findViewById(R.id.textView_name);
         final Button favoritebutton = (Button) view.findViewById(R.id.tgbFav);
         buttonInfo.setOnClickListener(new View.OnClickListener() {
                 String tag = v.getTag().toString();
                if(tag != null) {
                    int i = Integer.parseInt(tag);
                    System.out.println(tag);
                 }
            }
        });


private ArrayList<String> names;
private SharedPreferences sharedPreferences;

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String favoriteItems = sharedPreferences.getString("FAVORITE_ITEMS", "");

 if(favoriteItems.isEmpty())
    names = new ArrayList<>();
    else
      names = new ArrayList<>(Arrays.asList(favoriteItems.split(","));  //Update like this

      favoritebutton.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick( View v) {
        if (!names.contains(textView_name.getText())){
            names.add((String) textView_name.getText());

            for (int i=0; i<names.size(); i++) {
                System.out.println(names.get(i));
                favoritebutton.setBackgroundResource(R.drawable.fav_checked);
            }
        }
        else {
            System.out.println(textView_name.getText() + "   is already present in the Array at index " + names.indexOf(textView_name.getText()));
            int currentIndex = names.indexOf(textView_name.getText());
            names.remove(currentIndex);
            for (int i=0; i<names.size(); i++) {
                System.out.println(names.get(i));
                favoritebutton.setBackgroundResource(R.drawable.star_off);
            }
        }

        sharedPreferences.edit().putString("FAVORITE_ITEMS", TextUtils.join(",", names)).apply();
    }
});

 <ToggleButton
        android:id="@+id/tgbFav"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:focusable="false"
        android:focusableInTouchMode="false"

        android:textOff=""
        android:layout_toLeftOf="@+id/button"
        android:textOn=""/>

2 Answers2

0

When you scroll the ListView, the few visible view items will be reused for the entire list. If you aren't handling the getView correctly, the item that was previously used for a name without favorite will be reused for a name that is set as favorite. Hence, it will look like the favorite button gets unchecked while scrolling the ListView. You have to keep track of the favorite status of all the names and use it in getView to show the proper UI.

Now, when the favoritebutton is clicked, you are updating it's background, and updating the ArrayList "names". You need to use this ArrayList in your getView, check the current favorite status of the name, and use that to set the proper background resource for the favoritebutton in your getView.

Bob
  • 13,447
  • 7
  • 35
  • 45
  • can u implement with an example – sajjad ahmad Dec 13 '19 at 07:26
  • Check this answer for example: https://stackoverflow.com/a/34024509/4586742 – Bob Dec 13 '19 at 09:24
  • initialize this array on creation of your adapter with the same size as your listView , the mentioned answer shows to initialize the array with the same size but here the size of array changes with selecting and removing item from favorite array – sajjad ahmad Dec 13 '19 at 15:02
  • private boolean[] favorites; how would i initialize this – sajjad ahmad Dec 13 '19 at 15:03
  • No need to use array. ArrayList is fine. The point is you have to check the favorite status of each name and set the proper UI in your getView method. – Bob Dec 13 '19 at 15:08
  • 1
    How? can u please update the answer i am stuck from a week i have to get through this problem please solve this. – sajjad ahmad Dec 13 '19 at 15:17
0

Mate, what i have get from your question and snippet you post is you're saving all the favourite item name in shared-preference. But as you know you get that 'FAVORITE_ITEMS' in onCreate so it will only provide you the previously added favourite item. And in your you know if your scroll list view the item get update because getView() called for every item as such your favourite item that you clicked only seems as favourite until you didn't scroll list. For showing that item you need to check your item is present in favourite items or not for that add this snippet in your getView()

@Override
public View getView(final int i, View view, ViewGroup viewGroup) {

  Your code.... 

  String favoriteItems = sharedPreferences.getString("FAVORITE_ITEMS", "");  
  if (favoriteItems.contains(textView_name.getText())) {
      favoritebutton.setBackgroundResource(R.drawable.fav_checked);
  } else {
      favoritebutton.setBackgroundResource(R.drawable.star_off);
  }

  ....

}

Remember to notify list when any favouriteButton clicked.

Abhishek
  • 329
  • 3
  • 12
  • still the same proble when i scroll down the fav_checked is updated – sajjad ahmad Dec 13 '19 at 08:11
  • how would i notify the list., here by implementing the above code. and removing all the previous code for R.drawable.star_off/fav_checked a favorite button with star_off icon and by pressing the button nothing happens the button icon doesn't changes – sajjad ahmad Dec 13 '19 at 15:09