I have a list of exercises. When you click on one exercise, the exercise's details appears (infos from sqlite, communication using intent). There is also a button for deleting exercise and here is my problem, how can I delete exercise using that button?
Here is some code that may be useful to solve my problem. I tried to send my ID to ListDetails and then on clicking button send it back to ListExercisesFragment:
ListExercisesFragment class
private ArrayList<Exercise> lExercise=new ArrayList<Exercise>();
private CustomListAdapter dataAdapter;
private static final int REQUEST_CODE=100;
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent,View view,int position,long id){
Exercise exercise=(Exercise) listView.getItemAtPosition(position);
Intent intent = new Intent(getContext(),ListDetail.class);
intent.putExtra("id",exercise.getId());
intent.putExtra("name",exercise.getName());
intent.putExtra("series",exercise.getSeries());
intent.putExtra("reps",exercise.getReps());
intent.putExtra("weights",exercise.getWeights());
intent.putExtra("notes",exercise.getNotes());
startActivityForResult(intent,REQUEST_CODE);
}
});
@Override
public void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode==REQUEST_CODE){
if(resultCode==getActivity().RESULT_OK){
long id=data.getLongExtra("id",-1);
if(id!=-1){
deleteExerciseWithID(id);
}
}
}
super.onActivityResult(requestCode,resultCode,data);
}
private void deleteExerciseWithID(long id){
for(Exercise e:lExercise){
if( e.getId()==id ){
dbHelper.deleteRowWithId(id);
lExercise.remove(e);
dataAdapter.notifyDataSetChanged();
}
}
}
ListDetail class
public class ListDetail extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_detail);
final long id=getIntent().getLongExtra("id",-1);
String name=getIntent().getStringExtra("name");
int series=getIntent().getIntExtra("series",-1);
int reps=getIntent().getIntExtra("reps",-1);
int weights=getIntent().getIntExtra("weights",-1);
String notes=getIntent().getStringExtra("notes");
TextView txtName=(TextView) findViewById(R.id.detail_name);
TextView txtSeries=(TextView) findViewById(R.id.detail_series);
TextView txtReps=(TextView) findViewById(R.id.detail_reps);
TextView txtWeights=(TextView) findViewById(R.id.detail_weights);
TextView txtNotes=(TextView) findViewById(R.id.detail_notes);
txtName.setText(name);
txtSeries.setText(Integer.toString(series));
txtReps.setText(Integer.toString(reps));
txtWeights.setText(Integer.toString(weights));
txtNotes.setText(notes);
Button btnDelete=(Button) findViewById(R.id.btn_delete);
btnDelete.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent intent=new Intent();
intent.putExtra("id",id);
setResult(RESULT_OK,intent);
finish();
}
});
}
Thanks in advice for any help, I hope it would be easy :)