Android : Custom CursorAdapter won't update after deleting rows in list view

on Saturday, September 13, 2014


After I click delete button, nothing happens. But when I re-enter my app, deleting gets done. The problem is, I don't know where to call restartLoader() to requery the cursor, so that it updates my listview. here's the code:



class WordsListCursorAdapter extends CursorAdapter {

private Context mContext;

public WordsListCursorAdapter(Context context, Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
mContext = context;
}

@Override
public void bindView(View view, Context context, final Cursor cursor) {
TextView theWord = (TextView) view.findViewById(R.id.list_item_theword);
TextView translatedWord = (TextView) view.findViewById(R.id.list_item_translated);
ImageButton deleteButton = (ImageButton) view.findViewById(R.id.deleteButton);

//final int itemId = cursor.getColumnIndex(DBContract.WordTable._ID);

deleteButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
new SQLiteCursorLoader(mContext).delete(DatabaseHelper.getInstance(mContext),
DBContract.WordTable.TABLE_NAME, null, null);
notifyDataSetChanged();
}
});

theWord.setText(cursor.getString(cursor.getColumnIndexOrThrow(DBContract.WordTable.THEWORD_COLUMN)));
translatedWord.setText(cursor.getString(cursor.getColumnIndexOrThrow(DBContract.WordTable.TRANSLATED_COLUMN)));
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context); // ?
return inflater.inflate(R.layout.words_list_item, parent, false);}}





public class WordsListFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{

private WordsListCursorAdapter cursorAdapter;
private ListView listView;
private SQLiteCursorLoader cursorLoader;

private final static int URL_WORDS_LOADER = 0;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_words_list, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);

cursorAdapter = new WordsListCursorAdapter(getActivity(), null, true);

listView.setEmptyView(rootView.findViewById(android.R.id.empty));
listView.setAdapter(cursorAdapter);

getLoaderManager().initLoader(URL_WORDS_LOADER, null, this);
return rootView;
}


@Override
public Loader<Cursor> onCreateLoader(int loaderID, Bundle bundle) {
cursorLoader = new SQLiteCursorLoader(getActivity(), DatabaseHelper.getInstance(getActivity()),
DBContract.WordTable.TABLE_NAME, null, null, null, null, null, null);
return cursorLoader;
}


@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
cursorAdapter.changeCursor(cursor);
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.changeCursor(null);
}


}


0 comments:

Post a Comment