onResponse布尔实例变量未设置?

时间:2016-04-19 17:39:58

标签: java android json boolean response

我有一个点击监听器,在点击监听器中,我有一个if,else语句,如下所示

  @Override
        public void onClick(View v) {
            postMethodRegister();
            System.out.println("mSuccess is set to " + mSuccess);
            if (mSuccess) {
                Intent login = new Intent(Login.this, MainActivity.class);
                startActivity(login);
            }else{
                Toast toast = Toast.makeText(getApplicationContext(), "Please Check your UserName or Password", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.show();
            }
        }

我还有一个布尔变量,默认情况下设置为false,private boolean mSuccess;如果onResponse被执行我将其设置为true,否则我将其设置为false并执行相应的响应,但由于某种原因,第一次登录尝试运行onResponse,但是当它到达onClick时mSuccess被设置为这是怎么回事? mSuccess是一个实例变量。

 public void postMethodRegister() {
    StringRequest request = new StringRequest(Request.Method.POST, loginUrl, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            System.out.println("On Response was thrown in Login"+response);
            mSuccess=true;
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println("Error was thrown in Login" + error.getMessage()+"and the response code is ");
            mSuccess=false;

        }
    })

1 个答案:

答案 0 :(得分:1)

postMethodRegister()方法发出异步请求。

因此,当您点击按钮onClick()时,会调用postMethodRegister()来调用postMethodRegister()。 然后postMethodRegister()发出异步网络请求,这意味着您的网络请求将在另一个线程中运行,然后您的控件将立即移至System.out.println("mSuccess is set to " + mSuccess); onResponse()之后的下一行。现在,由于您没有得到mSuccess的回复,因此tvEvidenceID[i] = new TextView(context);将保持不变(并且将为false)。