如何按顺序发送多个截击请求并在单个侦听器中处理它们 [英] How to send multiple volley request in a sequence and handle them in a single listener

查看:47
本文介绍了如何按顺序发送多个截击请求并在单个侦听器中处理它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我需要按顺序发送多个截击请求. 我已经创建了一个用于处理截击响应的通用侦听器.

In my application I need to send multiple volley request in a sequence. I've create a common listener for dealing with the volley response.

public interface RequestCallBack {
    void onSuccess(JSONObject jsonObject, String tag)
    void OnError(String message);
}

并使用方法注册此回调:

And registered this callback using method:

public void setOnResponseListener (RequestCallBack onResponseListener) {
    this.onResponseListener = onResponseListener;
}

我创建了一个处理排球请求的常用方法.

I've created a common method in which volley request is handle.

public void getResponse(String tag, String url) {
    JsonObjectRequest jsonObjectRequest;
    try {

        jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                url,null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {

                try {
                    mStatusCode = response.optInt("status_code");
                    mBody = response.optJSONObject("body");
                    if (mStatusCode != 0 && mStatusCode == 201) {
                        onResponseListener.onSuccess(mBody, (String) jsonObjectRequest.getTag());
                    }

                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                onResponseListener.OnError(displayVolleyError(error));
            }
        }) {
            @Override
            protected VolleyError parseNetworkError(VolleyError volleyError) {
                if (volleyError.networkResponse != null && volleyError.networkResponse.data != null) {
                    volleyError = new VolleyError(new String(volleyError.networkResponse.data));
                }

                return volleyError;
            }
        };

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
                REQUEST_TIMEOUT_MS,
                NO_OF_RETRY_ATTEMPTS,
                BACK_OF_MULTIPLIER));
        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(jsonObjectRequest, tag);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

我从一个类中将该方法称为:

I've called this method from a class as:

    classObject.getResponse("request1", firstUrl);
    classObject.getResponse("request2", secondUrl);

并且我已经重写了RequestCallBack接口方法. 但是每次返回第二个请求的标记时,在 onSuccess 方法内部.

And I've overrided the RequestCallBack interface methods. But Inside the onSuccess Method each time the tag of 2nd request is returned.

@Override
public void onSuccess(JSONObject jsonObject, String tag) {
    Log.d("Class", "tag: "+tag); // Always returns the "request2"
    // Will check service response according to tag
    // but didn't get the right tag.
}

@Override
public void OnError(String message) {

}

有人可以在这里建议我如何解决此问题.

Can anyone suggest me here how to resolve this issue.

先谢谢了.

推荐答案

应用程序类

import android.app.Application;
import android.text.TextUtils;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

/**
 * Created by Preetika on 7/4/2016.
 */
public class App extends Application {

    private static App  mInstance;
    public static final String TAG = App.class
            .getSimpleName();
    private RequestQueue mRequestQueue;
    public App() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;


    }
    public static synchronized App getmInstance(){return mInstance;}

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }
    public <T> void addToRequestQueue(com.android.volley.Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

}

创建一个枚举,以便您在遇到以下任何请求时都可以设置任何值.

Create an Enum So that you can set any value whenever you are going to hit any request like below.

public static enum SERVICE_TYPE{
       //set enums here for example you are hitting request for login 
       LOGIN
    }

我创建了一个用于在服务器上发送请求的通用类.

I have created a common class for sending requests on server.

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.acadgild.android.volley.App;
import com.acadgild.android.volley.utils.CommonUtilities;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;

import java.util.Map;

/**
 * Created by Preetika on 6/17/2016.
 */
public class CallAddrVolley extends AsyncTask<Void, Void, Void> {

    private static String TAG= "CallAddr";
    Context context;
    Map<String, String> paramss;
    OnWebServiceResult resultListener;
    CommonUtilities.SERVICE_TYPE Servicetype;
    String url;
    int method;
    private String tag_json_obj = "jobj_req";


    public CallAddrVolley(Context context, Map<String, String> params, int method, String url, CommonUtilities.SERVICE_TYPE Servicetype, OnWebServiceResult resultListener){
        this.context= context;
        this.paramss = params;
        this.url= url;
        this.resultListener= resultListener;
        this.Servicetype= Servicetype;
        this.method= method;
        Log.e("size", "size= "+ paramss.size());
    }


   @Override
    protected Void doInBackground(Void... params) {
     /*  JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
               url, null,
               new Response.Listener<JSONObject>() {

                   @Override
                   public void onResponse(JSONObject response) {
                       Log.d(TAG, response.toString());
                       try {
                           resultListener.getWebResponse(response.toString(), Servicetype);
                       }catch (Exception e){
                           e.printStackTrace();
                       }
                   }
               }, new Response.ErrorListener() {

           @Override
           public void onErrorResponse(VolleyError error) {
               VolleyLog.d(TAG, "Error: " + error.getMessage());
           }
       }) {

           *//**
            * Passing some request headers
            * *//*
           @Override
           public Map<String, String> getHeaders() throws AuthFailureError {
               HashMap<String, String> headers = new HashMap<String, String>();
               headers.put("Content-Type", "application/json");
               return headers;
           }

           @Override
           protected Map<String, String> getParams() {
               Log.e("params", "params= "+ paramss.size());
               Log.e("params", "params= "+ paramss.get(Constants.USER_ID));
               return paramss;
           }

       };*/
       StringRequest myReq = new StringRequest(method,
               url,
               new Response.Listener<String>() {
                   @Override
                   public void onResponse(String response) {
                       Log.e(TAG, response.toString());
                       try {
                           resultListener.getWebResponse(response.toString(), Servicetype);
                       }catch (Exception e){
                           e.printStackTrace();
                       }

                   }
               },
               new Response.ErrorListener() {

                   @Override
                   public void onErrorResponse(VolleyError error) {
                       VolleyLog.d(TAG, "Error: " + error.getMessage());
                   }
               }) {

           protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {

               Log.e("params", "params= "+ paramss.size());
               Log.e(TAG, "Url= "+ url+ paramss.toString());
               return paramss;
           };
       };
       // Adding request to request queue
       App.getmInstance().addToRequestQueue(myReq,
               tag_json_obj);
        return null;
    }

}

创建一个接口,您必须将该接口包含在您要命中请求的那些类中,以便可以获取结果,并且在CommonUtilities.SERVICE_TYPE的帮助下,您将知道结果来自服务

Create an interface that you have to include in those classes where you want to hit request so that you can get result and with the help of CommonUtilities.SERVICE_TYPE you will come to know that result is coming from service

 import com.acadgild.android.volley.utils.CommonUtilities;

    /**
     * @author Preetika
     *
     */
    public interface OnWebServiceResult {
        public void getWebResponse(String result, CommonUtilities.SERVICE_TYPE type);
    }

尝试一下,我正在我的项目中使用这种方法,它非常适合我...如果需要任何帮助,请告诉我....

Try it I am using this approach in my projects and it works for me perfectly... If any help is needed let me know....

这篇关于如何按顺序发送多个截击请求并在单个侦听器中处理它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆