5

What ever I do, I keep getting errors like null object reference when I try to call a toast inside a switch case. The class where the switch method is in extends FragmentActivity

I have tried to extends Fragment/v4. and Activity without succses. I also tried to pass the getContext, getBaseContext, getAppliction();, getApplication().getBaseContext etc as context to the toast without succses

if I create a public Toast object in my MainActivity and use it like this MainActivity.copyToast.show(); It work, but this solution dosen't look good.

I want to keep it in one line like this: Toast.makeText(this.getApplicationContext(), "Copied to clipboard.", Toast.LENGTH_SHORT).show();

The whole class:

public class CustomTextSelectionMenu extends Fragment implements android.view.ActionMode.Callback {



@Override
public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
    MenuInflater inflater = mode.getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);
    menu.removeItem(android.R.id.selectAll);
    menu.removeItem(android.R.id.paste);



    return true;
}

@Override
public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
    return false;
}

@Override
public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {

    int selectionStart = editText.getSelectionStart();
    int selectionEnd = editText.getSelectionEnd();

    if (selectionEnd > selectionStart) {
        Spannable str = editText.getText();
        boolean exists = false;
        StyleSpan[] styleSpans;

        switch (item.getItemId()) {


            //--------------------COPY----------------------------
            case android.R.id.copy:
                CharSequence charSequence =   editText.getText().subSequence(selectionStart, selectionEnd);
                ClipData clip = ClipData.newPlainText("simple text", charSequence);
                MainActivity.clipboard.setPrimaryClip(clip);



                Toast.makeText(getActivity().getApplicationContext(),  "Copied to clipboard.", Toast.LENGTH_SHORT).show();
                //MainActivity.copyToast.show();
                break;

            //--------------------BOLD----------------------------
            case R.id.bold:

                styleSpans = str.getSpans(selectionStart, selectionEnd, StyleSpan.class);

                // If the selected text-part already has BOLD style on it, then
                // we need to disable it
                for (int i = 0; i < styleSpans.length; i++) {
                    if (styleSpans[i].getStyle() == android.graphics.Typeface.BOLD) {
                        str.removeSpan(styleSpans[i]);
                        exists = true;
                    }
                }

                // Else we set BOLD style on it
                if (!exists) {
                    str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), selectionStart, selectionEnd,
                            Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                }

                editText.setSelection(selectionStart, selectionEnd);



                break;     

        }
    }
    return true;

}


@Override
public void onDestroyActionMode(android.view.ActionMode mode) {


}

}

STACKTRACE:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:110)
at org.m.muddzboy.QuoteCreator.CustomTextSelectionMenu.onActionItemClicked(CustomTextSelectionMenu.java:182)
at android.widget.Editor$SelectionActionModeCallback.onActionItemClicked(Editor.java:3228)

Line 182 points to this:

Toast.makeText(this.getApplicationContext(), "Copied to clipboard.", Toast.LENGTH_SHORT).show();

4 Answers4

6

Toast method can cause many issues we must take care of it this why I answer this question.

first context called be null and crash your app like in your case .

how to fix it : on create method keep reference from context

private Context mContext;

 @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
     mContext = getActivity()
}

second when showing toast may be fragment be destroyed how to make sure it will not crash

public void showToast(String msg) {
        if (YOR_FRAGMENT.this.isVisible() && msg != null & mContext != null)
            Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
    }

this will keep you away from toast crashes

hope this help

Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156
1

I use Toast in my fragment application like below and its Completely working.

Context context;

After find rootView

context = getActivity();

Toast.makeText(context, "Copied to clipboard.", Toast.LENGTH_SHORT).show();
Chirag Savsani
  • 6,020
  • 4
  • 38
  • 74
1

If you use fragment use following code.

Toast.makeText(getActivity(), "Copied to clipboard.", Toast.LENGTH_SHORT).show();

If activity use following code.

Toast.makeText(this, "Copied to clipboard.", Toast.LENGTH_SHORT).show();
Prathap Badavath
  • 1,621
  • 2
  • 20
  • 24
0

If you are using Fragment you need to try Toast code like below:

Toast.makeText(getActivity(), "Copied to clipboard.", Toast.LENGTH_SHORT).show();
pRaNaY
  • 24,642
  • 24
  • 96
  • 146
  • 1
    It dosn't work, I get this error: `Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference` –  Dec 16 '15 at 12:46
  • @pRaNaY's answer is correct. Your comment and the error you are observing has nothing to do with the original question since you are getting a `NullReferenceException` on usage of the `getResources()` method and there's no `getResources()` in your (demo) code. If you have other problems, please post (a) new question(s). And please, read this: https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it before asking other questions related to `NullReferenceException` – Nikola Dec 16 '15 at 13:01
  • @Nikola I didn't vote his answer down, I just wrote what the result of his solution was, and that was the error I posted in the comment. And yes my comments and errors has to do the with the original question? People are providing me with their solutions and I'm giving feedback on them –  Dec 16 '15 at 13:08
  • @Muddz But now you are on different track, First clear what is your main problem ? `'android.content.Context android.content.Context.getApplicationContext()' on a null object reference` this one or ` java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference` this one? – Chirag Savsani Dec 16 '15 at 13:12
  • @ChiragSavsani Well right now its `android.content.res.Resources android.content.Context.getResources()' on a null object reference` when I try call : `Toast.makeText(getActivity(), "Copied to clipboard.", Toast.LENGTH_SHORT).show();` –  Dec 16 '15 at 13:15