【问题标题】:How to create a single volley webservice class to use across the android app?如何创建单个 volley webservice 类以在整个 android 应用程序中使用?
【发布时间】:2019-05-30 11:24:40
【问题描述】:

我的 android 应用程序在一个活动中使用多个网络调用,我有几个这样的活动,我必须同时使用 post 和 get 请求。我想创建一个“VolleyWebservice”类并在多个活动中调用相同的类,而不是编写完整的 volley 代码。我对 android 开发比较陌生,我不明白我哪里出错了。

public class VolleyWebService {

public JSONObject result;

public JSONObject getResponse(String url, Context mContext) {
    RequestQueue mQueue = Volley.newRequestQueue(mContext);
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.e(TAG, "Anshuman" + response.toString());

            result =  response;
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                }
            });

    mQueue.add(request);
   return result;
}
}

我正在调用此类的我的活动中的方法

    private void callFunctionGetDist() {
    ProgressDialog progressDialog;
    progressDialog = ProgressDialog.show(recorddata.this, "", "Please Wait...", true);
    JSONObject response = new VolleyWebService().getResponse(urlConfigClass.GET_DISTRICT, this);
    try {
        if(response.toString().contains("Status:Success,Details")){
            arrDistName.clear();
            arrDistCode.clear();
            arrDistName.add("Select District Name");
            arrDistCode.add("Select District Code");
            JSONArray jsonArray = response.getJSONArray("Status:Success,Details");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jobJ = jsonArray.getJSONObject(i);
                String scheName = jobJ.getString("post");
                JSONObject jobJDist = new JSONObject(scheName);
                String distname = jobJDist.getString("District");
                String distcode = jobJDist.getString("DistrictCode");
                arrDistName.add(distname);
                arrDistCode.add(distcode);
            }
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(recorddata.this,
                    R.layout.custom_textview_to_spinner, arrDistName);
            // Drop down layout style - list view with radio button
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            // attaching data adapter to spinner
            district.setAdapter(dataAdapter);
            progressDialog.dismiss();
        }else{
            progressDialog.dismiss();
            Toast.makeText(getApplicationContext(), "Response is null or empty", Toast.LENGTH_LONG).show();
        }
    } catch (Exception volleyError) {
        progressDialog.dismiss();
        Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
    }
}

我尝试创建相同的课程,但无法获得对其他活动的响应。虽然我在 Volley jsonbject 响应中得到了正确的响应,但在其他活动中响应返回 null。

我想让结果对象在我的记录数据活动中返回响应

这是我迄今为止尝试过的,但没有运气!

  public void postResponse (String url, Context mContext, final VolleyResponseListener listener) {
    try {
        String encodedUrl = url.replace(" ", "%20") + "";
        if (encodedUrl.contains("("))
            encodedUrl = encodedUrl.replace("(", "%28");
        if (encodedUrl.contains(")"))
            encodedUrl = encodedUrl.replace(")", "%29");
        encodedUrl = encodedUrl.replace(" ", "%20");

        RequestQueue mQueue = Volley.newRequestQueue(mContext);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POst, encodedUrl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.e(TAG, "Anshuman" + response.toString());

                listener.onSuccess(response);
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        listener.onError(error);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                return new HashMap<>();
            }

        };

        mQueue.add(request);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

【问题讨论】:

  • 您尝试过什么?请发布您的代码,以便我们帮助您对其进行迭代并具体确定您的问题。
  • 嘿,刚刚发布了我的 Volley 课程代码。请看一看。我希望“结果”jsonobject 在另一个类中返回截击响应。

标签: java android singleton android-volley


【解决方案1】:

为了实现你的目标,(不考虑架构和编码原则),你可以传递一个回调:

public class VolleyWebService {

public interface VolleyResponseListener {
  void onSuccess(JSONObject response);
  void onError(VolleyError error);
}

public JSONObject result;

public JSONObject getResponse(String url, Context mContext, VolleyResponseListener listener) {
    RequestQueue mQueue = Volley.newRequestQueue(mContext);
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.e(TAG, "Anshuman" + response.toString());

            listener.onSuccess(response);
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                   listener.onError(error);
                }
            });

    mQueue.add(request);
   return result;
}
}

使用它:

volleyWebService.getResponse("your url", context, new VolleyResponseListener() {
   @Override
   void onSuccess(JSONObject response) {
      //do what you want on success
   }

   @Override
   void onError(VolleyError error) {
      //do what you want on error
   }
});

【讨论】:

  • 关于如何对帖子请求执行相同操作的任何建议?
  • 你可以将它作为一个参数,或者为它创建另一个方法。试着玩一下。
  • 请看我的原帖。我已经发布了我的响应后课程。
猜你喜欢
  • 2013-12-30
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
  • 2020-09-26
相关资源
最近更新 更多