I've recently begun teaching myself Android development. Right now I'm making an app that shows a list of boxes; clicking on a box shows its contents. Each row view in the main list has a "delete" icon next to the box name. My ListAdapter is a subclass of CursorAdapter
. In the bindView()
method of CursorAdapter
, I do the following:
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView name = (TextView) view.findViewById(R.id.text_box_name);
name.setText(cursor.getString(cursor
.getColumnIndex(DatabaseContract.BoxEntry.NAME)));
name.setFocusable(false);
ImageButton delete = (ImageButton) view.findViewById(R.id.button_box_delete);
delete.setFocusable(false);
delete.setTag(cursor.getLong(0));
delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
long id = ((Long) view.getTag());
}
});
}
As you can see, I've tagged each ImageButton with the ID of the box it should delete. What I would like to be able to do here is this:
getContentResolver().delete(uri...);
This code would tell my custom ContentProvider
to delete that box and all its contents. The obvious problem is that from the context of my CursorAdapter
, I can't call getContextResolver
. What would be the best way to go about talking to my ContentProvider
from within the CursorAdapter
? Thanks in advance!
Context
contains the method getContentResolver() therefore you can write your bindView
as:
@Override
public void bindView(View view, final Context context, Cursor cursor) {
TextView name = (TextView) view.findViewById(R.id.text_box_name);
name.setText(cursor.getString(cursor
.getColumnIndex(DatabaseContract.BoxEntry.NAME)));
name.setFocusable(false);
ImageButton delete = (ImageButton) view.findViewById(R.id.button_box_delete);
delete.setFocusable(false);
delete.setTag(cursor.getLong(0));
delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
long id = ((Long) view.getTag());
context.getContentResolver().delete(uri...);
}
});
}
Note that your context
must be final
in order to reference it in the anonymous inner class.