【问题标题】:How to make separate class for volley library and call all method of volley from another activity and get response?如何为 volley 库创建单独的类并从另一个活动中调用 volley 的所有方法并获得响应?
【发布时间】:2016-06-08 06:38:52
【问题描述】:

如何创建一个单独的类,在其中定义所有关于 volley 在另一个活动中,我们直接传递 URL、CONTEXT 和 Get Response...

【问题讨论】:

    标签: android android-volley


    【解决方案1】:

    首先在Activity中创建回调接口获取结果

    public interface IResult {
        public void notifySuccess(String requestType,JSONObject response);
        public void notifyError(String requestType,VolleyError error);
    }
    

    使用 volley 函数创建一个单独的类,通过接口响应结果到活动

    public class VolleyService {
    
        IResult mResultCallback = null;
        Context mContext;
    
        VolleyService(IResult resultCallback, Context context){
            mResultCallback = resultCallback;
            mContext = context;
        }
    
    
        public void postDataVolley(final String requestType, String url,JSONObject sendObj){
            try {
                RequestQueue queue = Volley.newRequestQueue(mContext);
    
                JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if(mResultCallback != null)
                            mResultCallback.notifySuccess(requestType,response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if(mResultCallback != null)
                            mResultCallback.notifyError(requestType,error);
                    }
                });
    
                queue.add(jsonObj);
    
            }catch(Exception e){
    
            }
        }
    
        public void getDataVolley(final String requestType, String url){
            try {
                RequestQueue queue = Volley.newRequestQueue(mContext);
    
                JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if(mResultCallback != null)
                            mResultCallback.notifySuccess(requestType, response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if(mResultCallback != null)
                            mResultCallback.notifyError(requestType, error);
                    }
                });
    
                queue.add(jsonObj);
    
            }catch(Exception e){
    
            }
        }
    } 
    

    然后将回调接口初始化为主Activity

        mResultCallback = new IResult() {
            @Override
            public void notifySuccess(String requestType,JSONObject response) {
                Log.d(TAG, "Volley requester " + requestType);
                Log.d(TAG, "Volley JSON post" + response);
            }
    
            @Override
            public void notifyError(String requestType,VolleyError error) {
                Log.d(TAG, "Volley requester " + requestType);
                Log.d(TAG, "Volley JSON post" + "That didn't work!");
            }
        };
    

    现在创建 VolleyService 类的对象并传递给它上下文和回调接口

    mVolleyService = new VolleyService(mResultCallback,this);
    

    现在调用 Volley 方法进行发布或获取数据,同时传递 requestType,用于在将结果返回到主活动时识别服务请求者

        mVolleyService.getDataVolley("GETCALL","http://192.168.1.150/datatest/get/data");
        JSONObject sendObj = null;
    
        try {
            sendObj = new JSONObject("{'Test':'Test'}");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj);
    

    最终的 MainActivity

    public class MainActivity extends AppCompatActivity {
        private String TAG = "MainActivity";
        IResult mResultCallback = null;
        VolleyService mVolleyService;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initVolleyCallback();
            mVolleyService = new VolleyService(mResultCallback,this);
            mVolleyService.getDataVolley("GETCALL","http://192.168.1.150/datatest/get/data");
            JSONObject sendObj = null;
    
            try {
                sendObj = new JSONObject("{'Test':'Test'}");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj);
        }
    
        void initVolleyCallback(){
            mResultCallback = new IResult() {
                @Override
                public void notifySuccess(String requestType,JSONObject response) {
                    Log.d(TAG, "Volley requester " + requestType);
                    Log.d(TAG, "Volley JSON post" + response);
                }
    
                @Override
                public void notifyError(String requestType,VolleyError error) {
                    Log.d(TAG, "Volley requester " + requestType);
                    Log.d(TAG, "Volley JSON post" + "That didn't work!");
                }
            };
        }
    
    }
    

    在以下链接中找到整个项目

    https://github.com/PatilRohit/VolleyCallback

    【讨论】:

    • 如何在单个 Activity 中调用多个 Api?
    • 太棒了..谢谢:)
    • 谢谢,我必须添加空参数。 JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url,null, new Response.Listener()
    • 是可行的..但是使用这种方法发布数据时如何添加参数?你能给我提示吗?
    • get 调用 iis 工作..但是 post 调用不起作用,那么使用这种方法发布数据时如何添加参数?你能给我提示吗?
    【解决方案2】:

    JsonParserVolley.java

    (我们将获得响应的单独类)

    public class JsonParserVolley {
    
    final String contentType = "application/json; charset=utf-8";
    String JsonURL = "Your URL";
    Context context;
    RequestQueue requestQueue;
    String jsonresponse;
    
    private Map<String, String> header;
    
    public JsonParserVolley(Context context) {
        this.context = context;
        requestQueue = Volley.newRequestQueue(context);
        header = new HashMap<>();
    
    }
    
    public void addHeader(String key, String value) {
        header.put(key, value);
    }
    
    public void executeRequest(int method, final VolleyCallback callback) {
    
        StringRequest stringRequest = new StringRequest(method, JsonURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                jsonresponse = response;
                Log.e("RES", " res::" + jsonresponse);
                callback.getResponse(jsonresponse);
    
    
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
    
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
    
                return header;
            }
        }
        ;
        requestQueue.add(stringRequest);
    
    }
    
    public interface VolleyCallback
    {
        public void getResponse(String response);
    }
    

    }

    MainActivity.java (onCreate方法中编写的代码片段)

    final JsonParserVolley jsonParserVolley = new JsonParserVolley(this);
        jsonParserVolley.addHeader("Authorization", "Your value");
        jsonParserVolley.executeRequest(Request.Method.GET, new JsonParserVolley.VolleyCallback() {
    
            @Override
            public void getResponse(String response) {
    
                jObject=response;
                Log.d("VOLLEY","RES"+jObject);
    
                parser();
            }
        }
        );
    

    parser()是获取的json响应用于绑定activity组件的方法。

    【讨论】:

      【解决方案3】:

      您实际上错过了上述 VolleyService 类中的一个参数。你需要包括,它是,... JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url,null,new Response.Listener() { /..../ } null 是应该包含的参数,否则它会给出错误

      【讨论】:

      • 感谢您的建议.. 但不要担心超类构造函数会自动为空对象请求执行此操作,因此无需通过,您也不能通过!!!
      【解决方案4】:

      在活动或片段中创建监听器(因为它们是接口,它们不能被实例化,但它们可以被实例化为实现接口的匿名类)。并将此实例作为参数传递给请求。(StringRequest、JsonObjectRequest 或 ImageRequest)。

      public class MainActivity extends Activity {
      
      private static final String URI = "";
      // This is like BroadcastReceiver instantiation
      private Listener<JSONObject> listenerResponse = new Listener<JSONObject>() {
      
          @Override
          public void onResponse(JSONObject arg0) {
              // Do what you want with response
          }
      };
      
      private ErrorListener listenerError = new ErrorListener() {
          @Override
          public void onErrorResponse(VolleyError arg0) {
              // Do what you want with error
          }
      };
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
      }
      

      }

      接下来,创建一个有 request 的类,并将这个监听器传递给这个类的 request 方法,仅此而已。我不解释这部分这与在任何教程中创建请求对象相同。但是您可以根据需要自定义此类。您可以创建单例RequestQueue 来检查优先级,或者将body http body 参数设置为此方法作为参数。

      public class NetworkHandler {
      public static void requestJSON(Context context, String url, Listener<JSONObject> listenerResponse,  ErrorListener listenerError) {
      
          JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, listenerResponse, listenerError);
      
          Volley.newRequestQueue(context).add(jsonRequest);
      }
      

      }

      【讨论】:

        【解决方案5】:
        public class VolleyService {
        
            IResult mResultCallback = null;
            Context mContext;
        
            VolleyService(IResult resultCallback, Context context)
            {
                mResultCallback = resultCallback;
                mContext = context;
            }
        
            //--Post-Api---
            public void postDataVolley(String url,final Map<String,String> param){
                try {
                    StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            if(mResultCallback != null)
                                mResultCallback.notifySuccessPost(response);
                        }
                    },  new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            if(mResultCallback != null)
                                mResultCallback.notifyError(error);
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            return param;
                        }
        
                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            Map<String, String> params = new HashMap<String, String>();
                            params.put("Content-Type", "application/x-www-form-urlencoded");
                            return params;
                        }
                    };
                    AppController.getInstance(mContext).addToRequestQueue(sr);
        
                }catch(Exception e){
        
                }
            }
            //==Patch-Api==
            public void patchDataVolley(String url,final HashMap<String,Object> param)
            {
                JsonObjectRequest request = new JsonObjectRequest(Request.Method.PATCH, url, new JSONObject(param),
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                if(mResultCallback != null)
                                    mResultCallback.notifySuccessPatch(response);
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                if(mResultCallback != null)
                                    mResultCallback.notifyError(error);
                            }
                        }) {
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        HashMap<String, String> headers = new HashMap<String, String>();
                        return headers;
                    }
                };
                AppController.getInstance(mContext).addToRequestQueue(request);
            }
        }
        
        public interface IResult {
            void notifySuccessPost(String response);
        
            void notifySuccessPatch(JSONObject jsonObject);
        
            void notifyError(VolleyError error);
        
        }
        

        【讨论】:

        • 错误AppController.getInstance(mContext).addToRequestQueue(request);
        猜你喜欢
        • 1970-01-01
        • 2016-02-05
        • 1970-01-01
        • 2019-01-10
        • 1970-01-01
        • 2021-08-19
        • 2020-02-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多