草庐IT

android - 在 switch case 中获取 Toasts 的空对象引用错误

coder 2023-12-11 原文

无论我做什么,当我尝试在 switch case 中调用 toast 时,我总是收到类似 null object reference 的错误。 switch方法所在的类extends FragmentActivity

我尝试扩展 Fragment/v4。和 Activity 没有成功。 我还尝试将 getContext、getBaseContext、getAppliction();、getApplication().getBaseContext 等 作为上下文传递给 toast,但没有成功

如果我在我的 MainActivity 中创建一个公共(public) 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(), "复制到剪贴板。", Toast.LENGTH_SHORT).show();

最佳答案

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

这会让你远离 toast 崩溃

希望对你有帮助

关于android - 在 switch case 中获取 Toasts 的空对象引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34312300/

有关android - 在 switch case 中获取 Toasts 的空对象引用错误的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  3. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  4. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  5. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  6. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  7. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

  8. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  9. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

  10. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

随机推荐