setter

时间:2016-06-06 00:47:27

标签: java android nullpointerexception

我正在尝试做一个简单的操作:单击一个按钮并显示一个自定义的DialogFragment,但我得到一个NullPointExpection,我无法找出原因。

mAlertDialog.java:

public class mAlertDialog extends DialogFragment {

    TextView title;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_invalid_time, container, false);
        title = (TextView)view.findViewById(R.id.titleText);
        return view;
    }

    public void setTheTitle(String title) {
        this.title.setText(title);
    }
}

显示mAlertDialog:

mAlertDialog dialog = new mAlertDialog();
dialog.setTheTitle(getActivity().getString(R.string.invalidTimeTitle));
dialog.show(fm, "InvalidTime");

错误讯息:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
    at m.inschool8.Objects.mAlertDialog.setTheTitle(mAlertDialog.java:20)
    at m.inschool8.bSubjects.Fragment_Subjects$55.onClick(Fragment_Subjects.java:2654)
    at android.view.View.performClick(View.java:4780)
    at android.view.View$PerformClick.run(View.java:19866)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

2 个答案:

答案 0 :(得分:0)

您的标题 null ,直到显示DialogFragment导致 onCreateView 启动。因此改变顺序如下:

mAlertDialog dialog = new mAlertDialog();
dialog.show(fm, "InvalidTime");
dialog.setTheTitle(getActivity().getString(R.string.invalidTimeTitle));

答案 1 :(得分:0)

当您致电

时,title仍然为空
mAlertDialog dialog = new mAlertDialog();
dialog.setTheTitle(getActivity().getString(R.string.invalidTimeTitle));

所以你能做的就是

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_invalid_time, container, false);
        title = (TextView)view.findViewById(R.id.titleText);
        setTheTitle(getActivity().getString(R.string.invalidTimeTitle));

        return view;
    }

//调用它

mAlertDialog dialog = new mAlertDialog();
dialog.show(fm, "InvalidTime");