I'm currently working on a simple Android application which will allow a user to add/remove/delete a record from a sqlite DB using checkboxes. The main activity has a listview which renders objects from an exercise adapter. The adapter extends from cursor adapter. The issue I'm having is when selecting a checkbox, then scrolling down the list so that the checkbox is out of view, the state is lost. Here are extracts of my main activity and my exercise adapter:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbManager = new DBManager(this);
dbManager.open();
adapter = new ExerciseAdapter(this, dbManager.fetch());
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
public void deleteExercise(View view) {
for (int i = 0; i < adapter.getCount(); i++) {
CheckBox c = listView.getChildAt(i).findViewById(R.id.checkBox);
if (c.isChecked()) {
deleteIds.add(adapter.getItemId(i));
}
}
for (Long deleteId : deleteIds) {
dbManager.delete(deleteId);
adapter.update(dbManager.fetch());
}
}
ExerciseAdapter:
public class ExerciseAdapter extends CursorAdapter {
public ExerciseAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.exercise, parent, false);}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView exerciseTitle = view.findViewById(R.id.exerciseTitle);
TextView exerciseDesc = view.findViewById(R.id.exerciseDescription);
TextView exerciseDate = view.findViewById(R.id.exerciseDate);
// Extract properties from cursor
String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String desc = cursor.getString(cursor.getColumnIndexOrThrow("description"));
String date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
// Populate fields with extracted properties
exerciseTitle.setText(title);
exerciseDesc.setText(String.valueOf(desc));
exerciseDate.setText(String.valueOf(date));
}
public void update(Cursor cursor) {
this.swapCursor(cursor);
this.notifyDataSetChanged();
}
}
This is adopted code so would like to keep the classes similar to how they are now, unless there is no other option and a big change is required.
Thanks.
Aucun commentaire:
Enregistrer un commentaire