• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Need help with saving the states of checkboxes

SCB360

Lurker
Aug 3, 2018
5
0
I'm trying to save the selections of checkboxes when I open the app or go to a different activity, it is a simple program that shows a list of countries and flags that you can set as favorites, I just cannot see where I've gone wrong here:

Code:
public class MyAdapter extends ArrayAdapter<String> {

String[] names;
int[] flags;
Context mContext;

public MyAdapter(Context context, String[] countryNames, int[] countryFlags, String[] countryDetails) {
super(context, R.layout.listview_item);
this.names = countryNames;
this.flags = countryFlags;
this.mContext = context;
}

[USER=1021285]@override[/USER]
public int getCount() {
   return names.length;
}

@NonNull
[USER=1021285]@override[/USER]
public View getView(int position, View convertView, ViewGroup parent) {
   ViewHolder mViewHolder = new ViewHolder();
   final SharedPreferences sp = mContext.getSharedPreferences("FreshStart", 0);
   boolean shouldBeChecked = sp.getBoolean(names[position], false);

if (convertView == null) {
   LayoutInflater mInflater = (LayoutInflater) mContext.
           getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   convertView = mInflater.inflate(R.layout.listview_item, parent, false);
   mViewHolder.mFlag = (ImageView) convertView.findViewById(R.id.imageView);
   mViewHolder.mName = (TextView) convertView.findViewById(R.id.textView);
   mViewHolder.mCheckBox = convertView.findViewById(R.id.check_Box);

} else {
   mViewHolder = (ViewHolder) convertView.getTag();
}
mContext.getSharedPreferences("FreshStart",0);
mViewHolder.mFlag.setImageResource(flags[position]);
mViewHolder.mName.setText(names[position]);

mViewHolder.mCheckBox.setTag(names[position]);
convertView.setTag(mViewHolder);
mViewHolder.mCheckBox.setChecked(shouldBeChecked);


mViewHolder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
       sp.setBoolean(names[position], isChecked);
       buttonView.setSelected(isChecked);
       if (isChecked)
           Toast.makeText(mContext, "Saved as Favorite", Toast.LENGTH_SHORT).show();
       else
           Toast.makeText(mContext, "No Longer set as Favorite", Toast.LENGTH_SHORT).show();

   }
});

return convertView;
}

static class ViewHolder {
ImageView mFlag;
TextView mName;
CheckBox mCheckBox;
}
 
Last edited by a moderator:
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones