【问题标题】:Getting null object reference errors for Toasts in a switch case在 switch case 中获取 Toast 的空对象引用错误
【发布时间】:2016-07-28 19:53:14
【问题描述】:

无论我做什么,当我尝试在开关盒内调用 toast 时,都会不断收到类似 null object reference 的错误。 switch方法所在的类扩展了FragmentActivity

我已经尝试扩展 Fragment/v4。和没有成功的活动。 我还尝试将getContext, getBaseContext, getAppliction();, getApplication().getBaseContext etc 作为上下文传递给没有成功的吐司

如果我在我的 MainActivity 中创建一个公共 Toast 对象并像这样使用它MainActivity.copyToast.show(); 它可以工作,但这个解决方案看起来不太好。

我想把它放在一行中:Toast.makeText(this.getApplicationContext(), "Copied to clipboard.", Toast.LENGTH_SHORT).show();

全班:

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) {


}

}

堆栈跟踪:

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)

第 182 行指向这一点:

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

【问题讨论】:

  • 是你在片段中的代码吗?
  • this.getApplicationContext() 代替 this ......尝试将 getActivity() 作为上下文
  • Toast.makeText(getActivity(), "复制到剪贴板。", Toast.LENGTH_SHORT).show();
  • ....你到底为什么将 EditTexts 存储在静态变量中???
  • @CapDroid 此代码位于自定义 SelectionActionModeCallback 类中。 getActivity 不起作用

标签: android


【解决方案1】:

Toast 方法会导致很多问题,我们必须注意它,这就是我回答这个问题的原因。

第一个上下文称为 null 并像您的情况一样使您的应用崩溃。

如何修复它:在创建方法时保持上下文引用

private Context mContext;

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

第二个显示toast的时候可能会被fragment破坏如何保证不会crash

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

这将使您远离吐司崩溃

希望对你有所帮助

【讨论】:

    【解决方案2】:

    我在我的片段应用程序中使用 Toast,如下所示,它完全正常工作。

    Context context;
    

    找到rootView后

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

    【讨论】:

    • 它不起作用:Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
    • 这对我没有帮助
    • 尝试清理项目并重新运行
    • 帮了我一个片段
    【解决方案3】:

    如果您使用片段,请使用以下代码。

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

    如果活动使用以下代码。

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

    【讨论】:

      【解决方案4】:

      如果您使用Fragment,您需要尝试Toast 代码,如下所示:

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

      【讨论】:

      • 它不起作用,我收到此错误:Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
      • @pRaNaY 的回答是正确的。您的评论和您观察到的错误与原始问题无关,因为您在使用 getResources() 方法时获得了 NullReferenceException,并且您的(演示)代码中没有 getResources()。如果您有其他问题,请发布 (a) 新问题。在询问与NullReferenceException相关的其他问题之前,请阅读此内容:stackoverflow.com/questions/4660142/…
      • @Nikola 我没有否决他的答案,我只是写了他的解决方案的结果,这就是我在评论中发布的错误。是的,我的 cmets 和错误与原始问题有关吗?人们向我提供他们的解决方案,我正在对他们提供反馈
      • @Muddz 但是现在你在不同的轨道上,首先弄清楚你的主要问题是什么? 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference 这个还是 `java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on an null object reference`这个?
      • @ChiragSavsani 现在是android.content.res.Resources android.content.Context.getResources()' on a null object reference,当我尝试打电话时:Toast.makeText(getActivity(), "Copied to clipboard.", Toast.LENGTH_SHORT).show();
      猜你喜欢
      • 2018-08-11
      • 1970-01-01
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      相关资源
      最近更新 更多