为Volley制造回报价值?我有回电

时间:2016-02-10 14:47:09

标签: android json android-volley

Volley图书馆是如此疯狂和愚蠢...... 我实现了大部分操作,但是当返回客户(返回cliente)时返回null对象

事实证明,这是一个仍在运行的异步方法,无需等待方法返回值,因此它始终是null对象。 所以我必须添加不返​​回null对象? 你有我的班级

public class ClienteREST {
    private String URL_JSON;
    private Context context;
    String claveSeguridad;
    String nif;
    Cliente cliente;

    public ClienteREST(Context context) {
        this.context = context;
    }

    public Cliente dologin(final Cliente c) {
        claveSeguridad = c.getClaveSeguridad().toString();
        nif = c.getNif().toString();
        URL_JSON = Constantes.URL_JSON + Constantes.URL_API_CLIENTE + Constantes.URL_API_CLIENTE_LOGIN;

        final HashMap<String, String> parametros = new HashMap<String, String>();
        parametros.put("nif", nif);
        parametros.put("claveSeguridad", claveSeguridad);

        getResponse(
                Request.Method.POST,
                URL_JSON,
                new JSONObject(parametros),
                new VolleyCallback() {
                    @Override
                    public void onSuccessResponse(String result) {
                        try {
                            JSONObject r = new JSONObject(result);
                            cliente = new Cliente(r.getInt("id"), r.getString("nif"), r.getString("nombre"), r.getString("apellidos"), r.getString("claveSeguridad"), r.getString("email"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
        return cliente;
    }

    public void getResponse(int method, String URL, JSONObject jsonValue, final VolleyCallback callback) {
        RequestQueue queue = MySingleton.getInstance(context).getRequestQueue();
        StringRequest strreq = new StringRequest(
                method,
                URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String Response) {
                        callback.onSuccessResponse(Response);
                    }
                }

                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError e) {
                e.printStackTrace();
            }
        }
        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json; charset=utf-8");
                headers.put("nif", nif);
                headers.put("claveSeguridad", claveSeguridad);
                return headers;
            }
        };
        MySingleton.getInstance(context).addToRequestQueue(strreq);
    }
}

interface VolleyCallback {
    void onSuccessResponse(String result);
}

0 个答案:

没有答案