Kurlicue Kurlicue - 6 months ago 22
Android Question

Unexpected NullpointExpection inside a setter

I'm trying to do a simple operation: click a button and show a custom DialogFragment, but I'm getting a NullPointExpection and I can't figure out why.

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


Showing mAlertDialog:

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


Error message:

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)

Answer

Your title is null until the DialogFragment is shown causing onCreateView to kick-in. Hence change the order as below:

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