• 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
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:
The problem is, there is no code to save the state of the checkboxes.
 
hmm ok, I'll take a look at that, aside from this, as a quick look is there anything in my code that doesn't seem right?
 
Only that you might want to look at RecyclerView, which has the ViewHolder pattern baked into it.
 
Back
Top Bottom