在其他课程中获取Android Volley响应

时间:2014-01-23 23:36:31

标签: java android json android-volley

我正在尝试使用Volley作为DBA层来调用具有JSON对象的Web服务。由于此层位于活动和另一个服务层之下,因此它似乎无法正常工作。我会尝试解释一下我的设置:

MainActivity:

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

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;
                }
            };
        }

我希望这很清楚。 最后,我想从一个活动中使用ProductService :: getProduct(),并在一个变量中使用来自webservice的实际JSON响应,我稍后可以使用它。

然而,此刻,该行

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

甚至没有执行。我做错了什么?

2 个答案:

答案 0 :(得分:3)

我会尝试的是:

将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);
        }

而不是像这样打电话给你的活动:

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...
                    }
                });

答案 1 :(得分:1)

创建抽象类AppActivity

import androidx.appcompat.app.AppCompatActivity;

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

使用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);
    }
}

创建如下所示的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);
    }
}

希望有帮助。