我的适配器没有等待我的onResponse,我该如何解决这个问题?

时间:2016-08-17 23:42:54

标签: android json multithreading request

我正在努力获得"回复"或者来自网络的响应的长度是我的请求。

public class Replies {
private String questionId;
private VolleySingleton mVolleySingleton;
private RequestQueue mRequestQueue;
public int replies;


private String url;

//Predondition:Place the id of the questions into the constructor
//as well as the url
//Postcondition: counts the number of replies
public Replies(String questionId) {
    this.questionId = questionId;
    JsonRequestMethod();
}
public void JsonRequestMethod() {
    url = "sampleURl"
    mVolleySingleton = VolleySingleton.getInstance();
    mRequestQueue = mVolleySingleton.getRequestQueue();
    JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET,url, (String) null, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
           replies=response.length();
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println(error);

        }
    });
    mRequestQueue.add(request);

}
public String getReplies() {
    return replies+"";
}

} 此外,在我的适配器中,我在我的bindviewholder上有这行代码

  Replies replies=new Replies(currentSearch.getId());
    holder.replies.setText(replies.getReplies());

然而,它一直设置为0,因为它没有等待响应,响应不是0.我如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

也许你可以

public class Replies {

    ...

    private NetWorkFinishListener listener;


    void setListener(NetWorkFinishListener listener){

        this.listener = listener;

    }

    public interface NetWorkFinishListener{

        void onSuccess(int replies);

        void onFailed(VolleyError error);
    }

    JsonArrayRequest request = new    JsonArrayRequest(Request.Method.GET,url, (String) null, new       Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            replies=response.length();
            if(listener != null){
                listener.onSuccess(replies);
            }
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println(error);
            if(listener != null){
                listener.onFailed(error);
            }

        }
});


}

并且

Replies replies=new Replies(currentSearch.getId());
replies.setListener(new NetWorkFinishListener() {
        @Override
        public void onSuccess(int replies) {
            holder.replies.setText(replies.getReplies());
        }

        @Override
        public void onFailed(VolleyError error) {
            // do some thing
        }
    });
//holder.replies.setText(replies.getReplies());

但是有一个错误。

持有人可能不是原版。但是听众仍然运行成功()。

你可以使用view.setTag()来判断。