ThunderRoid ThunderRoid - 6 months ago 110
Android Question

DialogFragment callback to Target Fragment using interface

I am trying to send some data from a

dialogfragment
to the targeted
fragment
but its not working.

I have written the following code, but it through
exception
:

java.lang.NullPointerException: Attempt to invoke interface method 'void com.x.x.FragmentAlertDialog$Communicator.setI(java.lang.String)' on a null object reference


Code:

public class FragmentAlertDialog extends DialogFragment {

Communicator callback;

public interface Communicator {
void setI(String name);
}

public static FragmentAlertDialog newInstance(String id, int title, int items) {
FragmentAlertDialog frag = new FragmentAlertDialog();
Bundle args = new Bundle();
args.putString("id", id);
args.putInt("title", title);
args.putInt("items", items);
frag.setArguments(args);
return frag;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
callback = (Communicator) getTargetFragment();
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String id = getArguments().getString("id");
int title = getArguments().getInt("title");
String[] items = getResources().getStringArray(getArguments().getInt("items"));
switch (id) {
case MainActivity.DIALOG_1:
return new AlertDialog.Builder(getActivity())
.setTitle(title)
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
callback.setI("Important Data");
}
}).create();
}
return null;
}


Fragment Class

public class FragmentXYXY extends Fragment implements View.OnClickListener, FragmentAlertDialog.Communicator {

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.et_i:
DialogFragment newFragment = FragmentAlertDialog.newInstance(MainActivity.DIALOG_I, R.string.i_select, R.array.i_array);
newFragment.setTargetFragment(this, 0);
newFragment.show(getFragmentManager(), "dialog");
}
}

@Override
public void setI(String name) {
textI.setText(name);
}


Can anybody please help.
Thank you

Code Modified- newFragment.setTargetFragment(this, 0);

Answer

you have to call setTargetFragment

setTargetFragment(this, 0);

in order to get a reference FragmentXYXY, in your DialogFragment.

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.et_i:
            DialogFragment newFragment = FragmentAlertDialog.newInstance(MainActivity.DIALOG_I, R.string.i_select, R.array.i_array);
            newFragment.setTargetFragment(this, 0);
            newFragment.show(getFragmentManager(), "dialog");
    }
}