简体   繁体   English

从一种方法调用时,Android AlertDialog 不会显示,但会从同一活动中的另一种方法显示。 为什么?

[英]Android AlertDialog doesn't get displayed while calling from one method but it gets displayed from another method in the same activity. Why?

I am in an activity and I am trying to display an alert dialog.我正在参加一项活动,我正在尝试显示一个警报对话框。 The code is this:代码是这样的:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("xx");
        builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                built.dismiss();
            }
        });
        builder.setNegativeButton(R.string.giveup, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                built.dismiss();
            }
        });
        builder.setCancelable(true);
        built = builder.create();
        built.show();

The thing is, the same code is called in two different places in the activity and one works while the other doesn't!问题是,相同的代码在活动的两个不同地方被调用,一个有效而另一个无效! I don't understand because they are literally the same...我不明白,因为它们实际上是一样的......

There are questions like this in this site and I tried most of them.这个网站上有这样的问题,我尝试了其中的大部分。 I changed the this in the parameter to the activity name, I set a position, I put show() method, etc... I do not know how to proceed我把参数中的this改成了活动名称,我设置了一个位置,我放了 show() 方法等等......我不知道如何进行

And I put breakpoints in both of the places.我在这两个地方都设置了断点。 The working one goes smoothly.工作一帆风顺。 But when it does not get displayed, the breakpoint crashes at 'builder.create()'.但是当它没有显示时,断点会在 'builder.create()' 处崩溃。 It doesn't go further than this (it doesnt see the next breakpoint which is built.show).它不会比这更进一步(它没有看到下一个断点是built.show)。 It says "frames are not available"它说“框架不可用”

I found it.我找到了。 Just putting it here in case someone needs it.把它放在这里以防有人需要它。 I found it from here: Listener method (interface in Service) in my Activity doesn't want to display a simple message我从这里找到它: 我的活动中的侦听器方法(服务中的接口)不想显示简单的消息

The problem was that, I was calling the "not-working" one from an emitter.listener, thus it was not working on the correct thread.问题是,我从emitter.listener 调用了“not-working”,因此它没有在正确的线程上工作。 We need this to work on UI thread.我们需要它来处理 UI 线程。 When I added this:当我添加这个时:

runOnUiThread(new Runnable(){
        public void run(){
           showAlertDialog();
        }
    });

It worked!有效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM