Android: Spinner does not update after change of d

2019-08-03 00:31发布

问题:

In my app the spinne shows the active items (I use Loader of support library to load them). The init of spinner works fine and it shows only the active items.

But I got the followeing problem: When I edit the items in another activity and store them (active and deactivat some of them) an go back (Back-Button), then I see the "old" list of items in the spinner. The adapter get the new cursor with correct data, but the spinner does not refresh his list.

What can I do to refresh the spinner list?

In onCreate() I initialize the Spinner

_ItemSpinner = (Spinner) getView().findViewById(R.id.spn_itemss);
_ItemAdapter = new AdvancedCursorAdapter(
    getActivity(),
    R.layout.spinner_2line_item,
    null, _ColumnList, _ColumnViews, 0);
_ItemSpinner.setAdapter(_ItemAdapter);

In onResume() I start the loader initialisation

@Override
public void onResume() {
    getLoaderManager().initLoader(1, null, this);
    super.onStart();
}

In onLoadFinished(Loader<Cursor> loader, Cursor data) I swap the cursor for the adapter

_ItemAdapter.swapCursor(data);

回答1:

you can call the adapter's notifyDataSetChanged method



回答2:

Finally I found out, not why, but which, element destroy the refresh of the spinner.

I used two different URIs of the same ContentProvider for updating all items and showing only active items

  1. CONTENT_URI_ITEMS
  2. CONTENT_URI_ACTIVE_ITEMS

If I use the same URI for updating and showing (with needed active filter), the spinner list will be updated. If I use different URIs, the spinner shows old data.

I don't understand this behavior (the cursor returns correct number of items, but the spinner doesn't care), but I have a work around that works.

Store data:

getActivity().getContentResolver().update(
    RecordsContentProvider.CONTENT_URI_ITEMS,
    _Changes,
    COLUMN_ID + " =?",
    new String[] { String.valueOf(_ID) });

Before (get data) - doesn't work:

CursorLoader curLoader = new CursorLoader(this.getActivity(),
    RecordsContentProvider.CONTENT_URI_ACTIVE_ITEMS,
    _ITEMS_PROJECTION,
    null, null, null);

After (get data) - work:

CursorLoader curLoader = new CursorLoader(this.getActivity(),
    RecordsContentProvider.CONTENT_URI_ITEMS,
    _ITEMS_PROJECTION,
    COLUMN_IS_ACTIVE + " =1", null, null);

notifyDataSetChanged is not necessary, if the underlying ContentProvider do this for you like this: (getContext().getContentResolver().notifyChange(uri, null);)



回答3:

Have you tried:

getLoaderManager().restartLoader(0, null, this);

in your activity, just after making changes on a database.