为什么我的代码没有以正确的顺序执行?

时间:2017-01-03 18:45:32

标签: java android

在下面的代码中,您能否向我解释为什么在调用方法request_user_name()之前执行if语句中的块?以下代码的结果如下:

我在if语句

我在if语句之外

调用request_user_name() - 单击确定

chatbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(request_user_name())
            {
                System.out.println("I am inside the if statement");
                Intent intent = new Intent(MainActivity.this, ChatRoom.class); 
                intent.putExtra("room_name", "room"); 
                intent.putExtra("user_name", name);
                startActivity(intent);
            }
            System.out.println("I am outside the if statement");
        }
    });




 private Boolean request_user_name() {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Enter Name:");
    final EditText input_filed = new EditText(this);
    builder.setView(input_filed);
    final Holder<Boolean> accessChatRoom = new Holder<Boolean>(true); 
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            name = input_filed.getText().toString();
            System.out.println("request_user_name() called - OK clicked");
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            System.out.println("request_user_name() called - Cancel clicked");
            accessChatRoom.setValue(false);
        }
    });
    builder.show();
    return accessChatRoom.getValue();
}

2 个答案:

答案 0 :(得分:1)

你的代码没问题并按预期工作:当你调用该函数时,它会准备一个带有'回调'的对话框然后显示它:

builder.show();   

但代码继续立即(显示我不是模态阻塞调用,只显示)并且代码转到下一个语句:

return accessChatRoom.getValue()  

此时的值是默认设置的值。

代码具有正常行为:这是一个概念问题。

HTH

答案 1 :(得分:0)

块中的代码在request_user_name()方法调用之前没有执行;如果request_user_name()没有执行并返回true,则块中的代码根本不会执行。 I.E.,代码块中的打印输出仅在满足&#34; if&#34;之后执行。条件(在您的情况下,request_user_name())。尝试从request_user_name()方法中打印到控制台,以测试执行顺序。我的猜测是你的代码在request_user_name()方法中不是线程安全的。这有帮助吗?