I've struggled a while to update a Fragment
from a DialogFragment
after clicking the positive button. The Fragment
is added programmatically to an Activity
. When clicking the positive button in the dialog a NullPointerException raises, because the parent Fragment
could not be found.
(I don't use SupportFragments
.)
Any suggestions?
The parent Activity
:
public class ResultActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction().add(R.id.activity_result, ResultDetailsOneFragment.newInstance()).commit();
}
}
}
}
The layout of 'ResultActivity':
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_result"
tools:context="com.myApp.view.ResultActivity"
tools:ignore="MergeRootFrame" />
The layout of 'ResultDetailsOneFragment':
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fragment_result_details_one"
tools:context="com.myApp.view.ResultActivity$ResultDetailsOneFragment" >
<!-- ... -->
</RelativeLayout>
The interface for the callback:
public interface EditResultDialogListener {
void onDialogFinish();
}
The DialogFragment
:
public class EditDescriptionDialog extends DialogFragment {
@Override
protected void onDialogPositiveButtonClick(DialogInterface dialog, int which) {
EditResultDialogListener resultDetailsOneFragment
= (EditResultDialogListener) getFragmentManager().findFragmentById(R.id.fragment_result_details_one);
/* here's the NullPointerException */
resultDetailsOneFragment.onDialogFinish();
}
}
You are getting nullpointer exception because you are trying to find the fragment inside the dialog fragment.
What you need to do is ->
Set the target fragment when showing the dialog ...
dialogFragment.setTargetFragment(ResultDetailsOneFragment.this, MY_REQUEST_CODE);
dialogFragment.show(getFragmentManager(), "tag");
Then in your onDialogPositiveClick,
@Override
protected void onDialogPositiveButtonClick(DialogInterface dialog, int which) {
// Send event back to parent fragment
getTargetFragment().onActivityResult(MY_REQUEST_CODE, Activity.RESULT_OK, null);
}
So on dialog positive button click, the onActivityResult of your Fragment will be called. Make sure you override the onActivityResult in your fragment class.