0
I’m new in android development and have this doubt.
I’m creating a DialogFragment
with an interface to capture user choice.
This is my dialog box next to the interface:
public class Opcoes extends DialogFragment {
private String valor = "";
private OpcoesListener listener;
public void setValor(String valor) {
this.valor = valor;
}
public String getValor() {
return valor;
}
@Override
public void onAttachFragment(Fragment childFragment) {
super.onAttachFragment(childFragment);
try {
if (childFragment instanceof Opcoes) {
listener = (OpcoesListener) childFragment;
}
} catch (ClassCastException e) {
throw new ClassCastException(childFragment.toString() + "must implement OpcoesListner");
}
}
public interface OpcoesListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_opcoes, null);
builder.setView(view);
builder.setMessage("Minha mensagem");
builder.setPositiveButton(R.string.sim, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
setValor("positivo");
listener.onDialogPositiveClick(Opcoes.this);
}
});
return builder.create();
}
}
This is the passage in the fragment where I call the dialogue in the event of click
.
btnContinuar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (radioTodos.isChecked()) {
showNoticeDialog();
}
}
}
public void showNoticeDialog() {
DialogFragment dialog = new Opcoes();
dialog.show(getFragmentManager(), "Dialog");
}
This is the error it returns when I click the positive button in the dialog box.
E/Androidruntime: FATAL EXCEPTION: main Process: br.com.simtk.simtkrelatorio, PID: 9189 java.lang.Nullpointerexception: Attempt to invoke interface method 'void br.com.simtk.simtkreportario.util.Options$Opcoeslistener.onDialogPositiveClick(androidx.fragment.app.Dialogfragment)' on a null Object Reference at br.com.simtk.simtkreportario.util.Options$1.onClick(Options.java:70) at androidx.appcompat.app.Alertcontroller$Buttonhandler.handleMessage(Alertcontroller.java:167) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.Activitythread.main(Activitythread.java:6077) at java.lang.reflect.Method.invoke(Native Method) at com.android.Internal.os.Zygoteinit$Methodandargscaller.run(Zygoteinit.java:866) at com.android.Internal.os.Zygoteinit.main(Zygoteinit.java:756)
Any note to solve the problem is valid.
Related: What is Nullpointerexception and what are its main causes?
– Icaro Martins