I have a CustomAdapter for a listview and I need to save all checkbox states from an array of boolean using SharedPreferences, I would like to save the name of the trick (an Array of String) as the Key and the state for each trick.
Everytime the user change any state it needs to update inside the SharedPreference for the clicked trick.
I tried the two methods below to test but it didn't work, I don't know how to make this work.
storeArray() and loadArray().
public class CustomAdapter0 extends BaseAdapter {
public CustomAdapter0(String[] tricks, Context context) {
this.tricks = tricks;
this.context = context;
isClicked = new boolean[tricks.length];
for(int i = 0; i < isClicked.length; i++) isClicked[i] = false;
}
private String[] tricks;
private Context context;
private boolean[] isClicked;
private LayoutInflater layoutInflater;
@Override
public int getCount() {
return tricks.length;
}
@Override
public Object getItem(int i) {
return tricks[i];
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
View row = convertView;
if(convertView == null){
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.custom_listview_tricks, null);
}
TextView textView = row.findViewById(R.id.name_xml);
ImageButton imageButton = row.findViewById(R.id.unmastered_xml);
textView.setText(tricks[i]);
if (isClicked[i]) imageButton.setBackgroundResource(R.drawable.mastered);
else imageButton.setBackgroundResource(R.drawable.unmastered);
**loadArray**(tricks[i], context);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ImageButton clickedView = (ImageButton) view;
int clickedPosition = (int)clickedView.getTag();
isClicked[clickedPosition] = !isClicked[clickedPosition];
notifyDataSetChanged();
**storeArray**(isClicked, tricks, context);
}
});
imageButton.setTag(i);
return row;
}
public boolean **storeArray**(boolean[] array, String[] arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++)
editor.putBoolean(arrayName + "_" + i, array[i]);
return editor.commit();
}
public Boolean[] **loadArray**(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
Boolean array[] = new Boolean[size];
for(int i=0;i<size;i++)
array[i] = prefs.getBoolean(arrayName + "_" + i, false);
return array;
}
}
Aucun commentaire:
Enregistrer un commentaire