简体   繁体   English

Android/Java:有没有办法在监听器触发后调用方法的返回?

[英]Android/Java : Is there a way to call the return of the method after a listener triggered?

I'm using Volley to get a JSONObject from an HTTP Api.我正在使用 Volley 从 HTTP Api 获取 JSONObject。

My problem is that I want my method to wait for the Response Listener getting the result, otherwise my method is returning a null object.我的问题是我希望我的方法等待响应侦听器获得结果,否则我的方法将返回 null object。
I tried using synchronize wait and notify to achieve it, but it doesn't seem to work, the activity freezes after the isFinished.wait() and the listener doesn't trigger.我尝试使用同步等待和通知来实现它,但它似乎不起作用,活动在isFinished.wait()之后冻结并且侦听器没有触发。 Can you tell me what's wrong in my code?你能告诉我我的代码有什么问题吗?

public JSONObject query(String url) throws InterruptedException {
    finished=false;
    Req = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            synchronized (isFinished){
                Retour = response;
                finished = true;
                isFinished.notifyAll();
            }
        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            synchronized (isFinished){
                Retour = null;
                finished = true;
                isFinished.notifyAll();
            }
        }
    });
    Queue.add(Req);
    synchronized (isFinished) {
        while (!finished) {
            isFinished.wait();
        }
        return Retour;
    }
}

I solved it by changing the design, so the method doesn't return anything, but calls back a Consumer interface that then retrieve the Result into a class field Data :我通过更改设计解决了这个问题,因此该方法不返回任何内容,而是回调一个Consumer 接口,然后将 Result 检索到 class 字段Data中:

Consumer<JSONObject> cons = a -> Data=a;

The original code became:原来的代码变成了:

public void query(String url,Consumer<JSONObject> cons) {
    Req = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Retour = response;
            callb.accept(Retour);
        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Retour = null;
            callb.accept(null);
        }
    });
    Queue.add(Req);
}

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

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