简体   繁体   English

在另一个课程中获取Android Volley响应

[英]Get Android Volley response in another class

I'm trying to use Volley as a DBA layer to call a webservice that hadles JSON objects. 我正在尝试使用Volley作为DBA层来调用具有JSON对象的Web服务。 Because this layer is below the activity and another service layer, it doesn't seem to be working properly. 由于该层位于活动和服务层之下,因此它似乎无法正常工作。 I'll try to explain my setup: 我将尝试解释我的设置:

MainActivity: 主要活动:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ProductService productService = new ProductService();
    productService.getProduct();
}

ProductService.java: ProductService.java:

    public void getProduct() {
            JsonObjectRequest req = new JsonObjectRequest("http://echo.jsontest.com/name/Milk/price/1.23/", null, createMyReqSuccessListener(), createMyReqErrorListener());
            ApplicationController.getInstance().addToRequestQueue(req);
        }

        private Response.Listener<JSONObject> createMyReqSuccessListener() {
            return new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.v("response", response.toString());
                }
            };
        }

        private Response.ErrorListener createMyReqErrorListener() {
            return new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                   return;
                }
            };
        }

I hope that is clear enough. 我希望这很清楚。 In the end, I would like to use the ProductService::getProduct() from an activity and the the actual JSON response from the webservice in a variable which I can later use. 最后,我想使用活动中的ProductService :: getProduct()以及来自Web服务的实际JSON响应,并在一个变量中使用该变量,以后可以使用它。

However, at the moment, the line 但是,目前,

Log.v("response", response.toString());

doesn't even execute. 甚至没有执行。 What am I doing wrong? 我究竟做错了什么?

What I would try is this: 我会尝试的是这样的:

Declare getProduct as 将getProduct声明为

public void getProduct(Response.Listener<JSONObject> listener, 
                       Response.ErrorListener errlsn) {
            JsonObjectRequest req = new JsonObjectRequest("http://echo.jsontest.com/name/Milk/price/1.23/",null, listener, errlsn);
            ApplicationController.getInstance().addToRequestQueue(req);
        }

And than call in your activity like this: 而不是像这样调用您的活动:

productService.getProduct(
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                       variableFromActivity = response;
                       //Or call a function from the activity, or whatever...
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                       //Show error or whatever...
                    }
                });

Create an abstract class AppActivity 创建一个抽象类AppActivity

import androidx.appcompat.app.AppCompatActivity;

public abstract class AppActivity extends AppCompatActivity
{
    abstract void callback(String data);
}

Extend all your Activities using AppActivity 使用AppActivity扩展您的所有活动

public class MainActivity extends AppActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String url = "Your URL";

        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("Title", "Android Volley Demo");
            jsonBody.put("Author", "BNK");
        }
        catch (JSONException e) {
            System.out.println(e);
        }

        final String requestBody = jsonBody.toString();

        Messenger messenger = new Messenger(MainActivity.this);
        messenger.sendMessage(this, url, requestBody);

    }

    public void callback(String data)
    {
        System.out.println(data);
    }
}

Create Messenger class as below: 创建Messenger类,如下所示:

public class Messenger
{
    private AppActivity myActivity;

    public  Messenger(AppActivity activity)
    {
        myActivity = activity;
    }

    public void sendMessage(Context context, String url, final String requestBody)
    {
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(context);

        // Request a string response from the provided URL.
        StringRequest stringRequest =
                new StringRequest(
                        Request.Method.POST,
                        url,
                        null,
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                System.out.println(error);
                            }
                        }
                ) {
                    @Override
                    public String getBodyContentType() {
                        return "application/json; charset=utf-8";
                    }

                    @Override
                    public byte[] getBody() throws AuthFailureError {
                        try {
                            return requestBody == null ? null : requestBody.getBytes("utf-8");
                        }
                        catch (UnsupportedEncodingException uee) {
                            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                            return null;
                        }
                    }

                    @Override
                    protected Response<String> parseNetworkResponse(NetworkResponse response)
                    {
                        myActivity.callback(new String(response.data));

                        String responseString = "";
                        if (response != null) {
                            responseString = String.valueOf(response.statusCode);
                            // can get more details such as response.headers
                        }
                        return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
                    }
                };

        queue.add(stringRequest);
    }
}

Hope it helps. 希望能帮助到你。

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

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