Passing data from DialogFragment to ArrayAdapter in ListFragment

1.2k views Asked by At

I have ListFragment in which each row has button which after clicking opens dialogFragment in which user can choose 1 of 10 options (it is a listView of 10 options). I want to save this choice in SQLite database (it's already done) and reflect choice in the particular list row of ListFragment, immediately after dialogFragment vanishes. How to do that?

I read that article: http://developer.android.com/…/basics/fr…/communicating.html but don't know how to implement this idea in my case as in my case it is communication between two Fragments, ommiting Activity.

Situation explaation

1

There are 1 answers

5
Scott Cooper On BEST ANSWER

Assuming you are showing the Dialog from the ListFragment, you want to get a callback when the the user clicks OK. Create an interface in your Dialog that the fragment can implement, then call it when the user clicks on OK.

public class ConfirmDialog extends DialogFragment implements Dialog.OnClickListener {

public interface OnItemSelectedListener {
    void onItemSelected(final int itemId);
}

private OnItemSelectedListener mListener;

public ConfirmDialog() {
    //Empty constructor
}

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    //Do your setup here.
    return new AlertDialog.Builder(getActivity())
            .setTitle("MyTitle")
            .setMessage("Pick one")
            .setPositiveButton(R.string.ok, this)
            .setNegativeButton(R.string.cancel, this)
            .setView(R.layout.my_list_view)
            .create();
}

public void setOnItemSelectedListener(final OnItemSelectedListener listener) {
    mListener = listener;
}

@Override
public void onClick(DialogInterface dialog, int which) {
    if (mListener != null && which == Dialog.BUTTON_POSITIVE) {
        mListener.onItemSelected(/*Get the currently selected item from your listview*/0);
    }
}

This will pass the information back to your ListFragment, where you can update the SQL and refresh the list to reflect the changes you made.

Once you have updated the database you will need to update the list that the list adapter is looking at, most likely a re-query. Then you will need to call notifyDataSetChanged on the adapter and it should refresh.