One can also delete crimes from CrimePagerActivity, which is slightly different, since there are several pages open. I came up with this, because I had some problems changing the menu in CrimeFragment. First add the remove icon and add code to fragment_crime_list.xml. We don’t need a new menu but just show or hide, what we need to when adding or deleting a crime.
.....
<item
android:id="@+id/remove_crime"
android:icon="@drawable/ic_menu_remove"
android:title="@string/remove_crime"
app:showAsAction="ifRoom|withText" />
.....
Then add this code in CrimePagerActivity at the end.
// challenge
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.fragment_crime_list, menu);
menu.findItem(R.id.remove_crime);
menu.removeItem(R.id.new_crime);
return super.onCreateOptionsMenu(menu);
}
In CrimeListFragment add a line of code at the end of the onCreateOptionsMenu
..........
subtitleItem.setTitle(R.string.show_subtitle);
}
// challenge
menu.removeItem(R.id.remove_crime);
}
In CrimePagerActivity create these two variables.
private Crime removeCrime;
private int rCrime = -1;
To get the correct crime, change the getItem function.
@Override
public Fragment getItem(int position) {
Crime crime = mCrimes.get(position);
// challenge
if (rCrime == -1) {
rCrime = position;
removeCrime = crime;
}
return CrimeFragment.newInstance(crime.getId());
}
Then add the onOptionsItemsSelected function after the onCreateOptionsMenu. See the comments for differences to CrimeFragment.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.remove_crime:
// Delete from CrimeLab
CrimeLab crimeLab = CrimeLab
.get(getApplicationContext());// we have to use getApplicationContext() here.
crimeLab.deleteCrime(removeCrime);
// Make changes in CrimeListFragment
Intent intent = new Intent(this,
CrimeListActivity.class); // intent has to refer to this
startActivity(intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Finally add a delete function in CrimeLab.
// challenge
public void deleteCrime(Crime crime) {
String uuidString = crime.getId().toString();
mDatabase.delete(CrimeDbSchema.CrimeTable.NAME,
CrimeDbSchema.CrimeTable.Cols.UUID + " = ?",
new String[] { uuidString });
}