Help, please, gives an error when trying to call a dialog from the ClickableSpan method.
In MainActivity OnCreate I create an instance of the dialog:

 WordTranslateDialogFragment dialog = new WordTranslateDialogFragment(); 

And then inside the ClickableSpan method I try to call the dialog:

 public ClickableSpan getClickableSpan(final String word) { return new ClickableSpan() { String mWord;{ mWord = word; } @Override public void onClick(View v) { Log.d(TAG, "клик на " + mWord); dialog.show(getSupportFragmentManager(), "dlg1"); Log.d(TAG, "MainActivity. вызвал диалог ClickableSpan") ; } }; } 

The class of the dialogue itself:

  public class WordTranslateDialogFragment extends DialogFragment implements OnClickListener { final String LOG_TAG = "myLogs"; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getDialog().setTitle("Title!"); View v = inflater.inflate(R.layout.dialog1, null); v.findViewById(R.id.btnYes).setOnClickListener(this); return v; } public void onClick(View v) { Log.d(LOG_TAG, "Dialog 1: " + ((Button) v).getText()); dismiss(); } } 

When you click on a word in the ClickableSpan method, the application closes and gives an error:

 NullPointerException: Attempt to invoke virtual method 'void my.soulfly.entraining.WordTranslateDialogFragment.show(android.support.v4.app.FragmentManager, java.lang.String)' on a null object reference 

pointing to the line dialog.show (getSupportFragmentManager (), "dlg1");

The same dialog is normally called if you hang it on a button inside OnCreate. How can I fix this?

  • 2
    In onCreate, you write a copy of the dialog in the local variable dialog, and where do you have it recorded in the dialog field that is used in onClick? Judging by the NullPointerException anywhere ... - xkor
  • No, I first declare the variable before OnCreate - soulfly84
  • I first declare the variable before OnCreate, and then inside it I create an instance of dialog = new WordTranslateDialogFragment (); If you immediately create a dialog object inside the ClickableSpan method, then you will get another error: Activity has been destroyed at android.support.v4.app.

0