从DialogFragment更新父片段会引发NullPointerException

时间:2014-10-28 13:47:23

标签: android android-fragments android-dialogfragment fragmentmanager

点击肯定按钮后,我已经挣扎了一段时间来更新Fragment DialogFragmentFragment以编程方式添加到Activity。单击对话框中的肯定按钮时,会引发NullPointerException,因为无法找到父Fragment。 (我不会使用SupportFragments。)

有什么建议吗?

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();
            }
        }
    }
}

' 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" />

&#39; ResultDetailsOneFragment&#39;的布局:

<?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>

回调界面:

public interface EditResultDialogListener {
    void onDialogFinish();
}

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();
    }
}

1 个答案:

答案 0 :(得分:1)

您正在获取nullpointer异常,因为您正在尝试在对话框片段中找到该片段。

您需要做的是 - &gt;

显示对话框时设置目标片段...

dialogFragment.setTargetFragment(ResultDetailsOneFragment.this, MY_REQUEST_CODE);
dialogFragment.show(getFragmentManager(), "tag");

然后在你的onDialogPositiveClick中,

@Override
protected void onDialogPositiveButtonClick(DialogInterface dialog, int which) {
    // Send event back to parent fragment
    getTargetFragment().onActivityResult(MY_REQUEST_CODE, Activity.RESULT_OK, null);
}

因此,在对话框上单击正面按钮,将调用Fragment的onActivityResult。 确保覆盖片段类中的onActivityResult。