An elegant way to handle LoaderCallbacks using DialogFragment

I have DialogFragmentone that uses a cursor for setMultiChoiceItems. This is Cursorobtained using LoaderManager.

What is the best way to handle this onCreateDialog method? The loader starts after calling this method, so the cursor is not available for AlertDialog.Builder at the beginning.

Is there a way to update the Dialog interface after calling onLoadFinished? Ideally, I would like to set the initial boot user interface, and as soon as Cursor becomes available, update the interface.

I have an implementation that works, which simply takes the cursor loading from the Fragment and into the Activity. I do not like it, although it is not very modular. I could write a Fragment class that would populate its own views and swap them when the cursor is finished, but that is also not very elegant.

Since this is more a design issue than a specific coding problem, I did not use a sample code. The answers I'm looking for should be based on how well to manage this kind of workflow in the DialogFragment class, using AlertDialog.Builder to create a Dialog view.

+4
source share
1 answer

An old question, but maybe the answer helps someone.

  • CursorLoader onCreate(), onCreateView onActivityCreated(), imo
  • onCreateDialog. .
  • onLoadFinished

:

public class MyDialogFragment extends DialogFragment implements LoaderManager.LoaderCallbacks<Cursor> {

    private CursorAdapter mAdapter;

    public static MyDialogFragment newInstance() {
        return new MyDialogFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLoaderManager().initLoader(0, null, this);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mAdapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_single_choice, null,
                    new String[] {FolderColumns.NAME}, new int[] {android.R.id.text1}, 0);

        return new AlertDialog.Builder(getContext())
                .setAdapter(mAdapter, null)
                .create();
    }

    @Override
    public synchronized Loader<Cursor> onCreateLoader(int id, Bundle args) {
        Uri uri = ...;
        return new CursorLoader(getActivity(), uri, null, null, null, null);
    }

    @Override
    public synchronized void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);
    }

    @Override
    public synchronized void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        if (cursor != null && !cursor.isClosed()) {
            mAdapter.swapCursor(cursor);
        }
    }

}

, onCreate, onCreateDialog onCreate.

+2

Source: https://habr.com/ru/post/1525830/


All Articles