用齐射

时间:2017-05-24 19:02:02

标签: java android http android-studio android-volley

我按照this问题在不同的活动中重复使用排球服务,但他只是使用JSONOBject来获取GET和POST请求,我需要返回一个JSONArray,因为我的请求会返回超过1个项目。

所以我的排球服务中有这样的东西:`public void

getDataVolley(final String requestType, String url){
        Log.d("TRIED","TRIED0");
        try {
            Log.d("TRIED","TRIED");
            RequestQueue queue = Volley.newRequestQueue(mContext);
        JsonArrayRequest jsonArray = new JsonArrayRequest(Request.Method.GET, url,null, new Response.Listener

() {

  @Override
        public void onResponse(JSONArray response) {
            Log.d("TRIED","TRIED2");
            if(mResultCallback != null)
                mResultCallback.notifySuccess(requestType, response);
        }
    }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("TRIED",error.toString());
            }
        });
        jsonArray.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(jsonArray);

    }catch(Exception e){
        Log.d("TRIED","TRIED4");
    }
}`

所以我在我的主要活动中使用此服务:

初始化

        initPlants();
    Log.d("RESULTCALL",mResultCallback.toString());

    mVolleyService = new VolleyService(mResultCallback,this);

    mVolleyService.getDataVolley(GETREQUEST,URL);

回调

void initPlants(){
        mResultCallback = new IResult() {

            @Override
            public void notifySuccess(String requestType, JSONArray response) {

            }

            @Override
            public void notifyError(String requestType,VolleyError error) {
                Log.d("GJJJ","GJJJ1");
            }
        };
    }

    public void showToast(String message){
        Toast toast = Toast.makeText(SimiliarPhotos.this,message, Toast.LENGTH_LONG);
        toast.show();
    }

问题是我的响应第二个参数(volleyService)出错,说它需要一个JsonObject。

我的IResult想要一个JSONObject而不是一个JSONArray

1 个答案:

答案 0 :(得分:0)

像这样修改您的界面

public interface IResult {
    public void notifySuccess(String requestType,JSONObject response);
    public void notifySuccess(String requestType,JSONArray response);
    public void notifyError(String requestType,VolleyError error);
}
// added a new method "notifySuccess" where params are requestType & JSONArray response

现在从你召唤你的凌空来到你的活动。来自" onCreate()"删除" initPlants();"方法。写下您的活动名称

public class Your_Activity extends Activity implements IResult {

现在实现覆盖方法,如

@Override
public void notifySuccess(String requestType, JSONObject response) {

}

@Override
public void notifySuccess(String requestType, JSONArray response) {
// Here You'll receive Your response as Array. Retrieve Your result from response
}

@Override
public void notifyError(String requestType,VolleyError error) {
    Log.d("GJJJ","GJJJ1");
}