Android - Wait for volley response to return

前端 未结 4 726
无人及你
无人及你 2020-12-08 10:39

I need execute a Volley request and wait for the response to parse it and return it, but have no idea on how to achieve this. Can someone help?

What I have now is th

4条回答
  •  囚心锁ツ
    2020-12-08 11:24

    You should probably not return the link in your method.

    Volley is doing asynchronous tasks, it means that you can't know when the answer will arrive from your webservice, it could be 10sec or 10min.

    If you need the string in your function you should probably create a method and call it when you have the result.

    Here is an example:

    I guess this is what you have

    public void getTheLinkAndCallDoSomething(){
        String link = getLink();
        doSomethingWithTheLink(link);
    }
    

    This would work if getLink() answers in a synchronous way. Volley is not in this case.

    And this is what you can do with Volley:

    public void getTheLinkAndCallDoSomething(){
         JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, 
                                   url, null, new Response.Listener() {
    
                        @Override
                        public void onResponse(JSONObject response) {
                            shortenURL = response.getString("url");
                            doSomethingWithTheLink(shortenURL);
                        }
                    }, new Response.ErrorListener() {
    
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // TODO Auto-generated method stub
    
                        }
                    });
    
        queue.add(jsObjRequest);
    }
    

    In this case, you call the WS to get your url. And as soon as the result is known, you call doSomethingWithTheLink()

    Whatever, if you really do want to be synchronous you can look at this post : Wait for result of Async Volley request and return it

    Also, be aware that waiting for an answer could freeze your app UI and I guess that is not what you want.

提交回复
热议问题