Android的排球 - 如何隔离在另一个类的请求 [英] Android Volley - How to isolate requests in another class

查看:124
本文介绍了Android的排球 - 如何隔离在另一个类的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我想模块化凌空请求,所以我不混活动presentation code与凌空请求。 所有的样品我看见了,凌空请求被放置 - 用于例 - 在OnClick事件从活动按钮。

Hi I'd like to modularize the volley requests so I don't mix activity presentation code with volley requests. All samples I saw, the volley request are being placed -for example- on the OnClick event from an activity button.

我的意思是code(摘自差异源):

I mean this code(taken from diff source):

// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
    new Response.Listener<JSONObject>() 
    {
        @Override
        public void onResponse(JSONObject response) {   
                        // display response     
            Log.d("Response", response.toString());
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {            
            Log.d("Error.Response", response);
       }
    }
);

// add it to the RequestQueue   
queue.add(getRequest);

我在这里的关键是如何让这一切都要求code到另一个类,只是实例类并调用makeRequest。 我已经尝试过这一点,但它失败。我不知道这是否是一些与环境相关的,但它失败...

My point here is how to get this all request code to another class and just instance the class and call the makeRequest. I already tried this but it fails. I don't know if it's something related with the Context but it fails...

我这样做:

public void onClick(View v) {
    try{

        Utils varRequest = new Utils(getApplicationContext());
        String url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";

        varRequest.makeRequest(url);
        mitexto.setText(varRequest.miError);
    }
    catch(Exception excepcion) {
        System.out.println(excepcion.toString());

        }

    }

...和utils的类:

... and the Utils class is:

public class Utils {
    public Context contexto;
    public String miError;
    private RequestQueue queue ;

    public Utils (Context contextoInstancia){
        contexto = contextoInstancia;
        queue = Volley.newRequestQueue(contexto);
    }

    public void makeRequest(String url){

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

            @Override
            public void onResponse(JSONObject response) {
                // TODO Auto-generated method stub
                miError="Response => "+response.toString();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
                miError="Response => "+error.networkResponse.toString();
            }
        });

        queue.add(jsObjRequest);
    }
}   

谁能告诉我什么,我做错了,或如何构建的code?

Can anyone tell me what I'm doing wrong, or how to structure the code?

在此先感谢。

推荐答案

在总体上是好的做法要分开这样的东西,所以你是在正确的道路上,考虑作出处理您的请求singelton类 - 这是一个很通用模板,但应该让你的结构会:

in general it's good practice to seperate this sort of stuff, so you're on the right path, consider making a singelton class that handles your requests - this is a very general template, but should get your structure going:

创建一个单独的类,你instatiate当你的应用程序出现:

create a singleton class, which you instatiate when you're application comes up:

public class NetworkManager
{
    private static final String TAG = "NetworkManager";
    private static NetworkManager instance = null;

    private static final String prefixURL = "http://some/url/prefix/";

    //for Volley API
    public RequestQueue requestQueue;

    private NetworkManager(Context context)
    {
        requestQueue = Volley.newRequestQueue(context.getApplicationContext());
        //other stuf if you need
    }

    public static synchronized NetworkManager getInstance(Context context)
    {
        if (null == instance)
            instance = new NetworkManager(context);
        return instance;
    }

    //this is so you don't need to pass context each time
    public static synchronized NetworkManager getInstance()
    {
        if (null == instance)
        {
            throw new IllegalStateException(NetworkManager.class.getSimpleName() +
                    " is not initialized, call getInstance(...) first");
        }
        return instance;
    }

    public void somePostRequestReturningString(Object param1, final SomeCustomListener<String> listener)
    {

        String url = prefixURL + "this/request/suffix";

        Map<String, Object> jsonParams = new HashMap<>();
        jsonParams.put("param1", param1);

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams),
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response)
                    {
                         Log.d(TAG + ": ", "somePostRequest Response : " + response.toString());
                         if(null != response.toString())
                           listener.getResult(response.toString());
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error)
                    {
                        if (null != error.networkResponse)
                        {
                            Log.d(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);
                            listener.getResult(false);
                        }
                    }
                });

        requestQueue.add(request);
    }
}

当您的应用程序出现:

public class MyApplication extends Application
{
  //...

    @Override
    public void onCreate()
    {
        super.onCreate();
        NetworkManager.getInstance(this);
    }

 //...

}

一个简单的侦听器接口回调(单独的文件会做很好的):

a simple listener interface for your callback (seperate file would do good):

public interface SomeCustomListener<T>
{
    public void getResult(T object);
}

最后,无论你想要的,背景是已经在那里,只要致电:

and finally, from wherever you want, the context is already in there, just call:

public class BlaBla
{
    //.....

        public void someMethod()
        {
            NetworkManager.getInstance().somePostRequestReturningString(someObject, new SomeCustomListener<String>()
            {
                @Override
                public void getResult(String result)
                {
                    if (!result.isEmpty())
                    {
                     //do what you need with the result...
                    }
                }
            });
        }
}

您可以使用任何对象的监听器,这取决于你需要接受(这也适用于一些小的修改GET请求),并调用来自世界各地(onClicks等),只rememeber他们需要之间的匹配的方法。

you can use any object with the listener, depending on what you need to receive (this also works for GET requests with some minor modification) and call that from everywhere (onClicks, etc.), just rememeber they need to match between methods.

希望这有助于并不算晚!

Hope this Helps and not too late!

这篇关于Android的排球 - 如何隔离在另一个类的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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