簡體   English   中英

為什么Android Volley不能首次使用?

[英]Why Android Volley doesn't work first time?

雖然Log.d總是顯示字符串(也是第一次),但是布爾值僅在我執行請求的第二次或更多次時才被占用。 我想第一次布爾值是真的。

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_UPDATE,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    //do stuffs with response of post
                    Log.d("Bien:",response.substring(0));
                    correctoExterna = true;
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //do stuffs with response erroe
                    correctoExterna = false;
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put("consulta",consultaExterna);
            return params;
        }

    };
    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
    requestQueue.add(stringRequest);
    if(correctoExterna) snackBar();

您的實現是異步的,這意味着因為回調尚未觸發,您的correctoExterna尚未更改。 如果您需要以同步方式實施,請使用FutureRequest

RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = new StringRequest(Request.Method.POST, URL_UPDATE, future, future){
    @Override
    protected Map<String,String> getParams(){
        Map<String,String> params = new HashMap<String, String>();
        params.put("consulta",consultaExterna);
        return params;
    }
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);

try {
  String response = future.get(); 
  Log.d("Bien:",response.substring(0));
  correctoExterna = true;
} catch (InterruptedException | ExecutionException e) {
  correctoExterna = false;
}

if(correctoExterna) snackBar();

也許您需要輸入“ if(correctoExterna)快餐吧();” 在“ public void onResponse(String response)”中和“ correctoExterna = true;”后面

在RequestQueue中添加StringRequest之后,它將在后台線程上執行,因此當您執行“ if(correctoExterna)SnackBar();”時,它可能不會調用onResponse回調方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM