我在其他课程中编写自定义Volley Android。但是我对此有疑问。这是我的定制排球课:
public class CustomVolley {
private Context _c;
public OnCallbackResponse OnCallbackResponse;
public interface OnCallbackResponse {
void OnVolleyErrorResponse(String TAG, String response);
void onVolleySuccessResponse(String TAG, String response);
}
public CustomVolley(Context c) {
_c=c;
}
public RequestQueue Rest(int METHOD, String URL, final Map<String, String> jsonParams , final String TAG) {
Log.v("URL "+TAG, URL);
RequestQueue queue = Volley.newRequestQueue(_c);
StringRequest sr = new StringRequest(METHOD, URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.v("onVolleySuccessResponse URL "+TAG, response);
if (OnCallbackResponse != null) {
OnCallbackResponse.onVolleySuccessResponse(TAG, response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
String resp="error";
if (response != null && response.data != null) {
resp = new String(response.data);
}
if (OnCallbackResponse != null) {
Log.v("OnVolleyErrorResponse URL "+TAG, resp);
OnCallbackResponse.OnVolleyErrorResponse(TAG, resp);
}
}
}) {
@Override
protected Map<String, String> getParams() {
return jsonParams;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
sr.setRetryPolicy(new DefaultRetryPolicy(
Variabel.MY_SOCKET_TIMEOUT_MS_NEWS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
sr.setShouldCache(false);
sr.setTag(TAG);
queue.add(sr);
return queue;
}
}
我这样叫我的活动:
public class GeneralBusinessActivity extends AppCompatActivity implements CustomVolley.OnCallbackResponse {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
context= getApplicationContext();
customVolley = new CustomVolley(context);
String url = "https://sds.com/api/search/detail/business?id_business=" + s_id_business + "&" + Variabel.app_key + "="
+ Variabel.value_app_key;
queue_getDetailResultBusiness = customVolley.Rest(Request.Method.GET, url, null, "getDetailResultBusiness");
}
@Override
public void OnVolleyErrorResponse(String TAG, String response) {
Toast.makeText(GeneralBusinessActivity.this, response, Toast.LENGTH_SHORT).show();
}
@Override
public void onVolleySuccessResponse(String TAG, String response) {
Toast.makeText(GeneralBusinessActivity.this, response, Toast.LENGTH_SHORT).show();
}
}
但这不是回调onError或onSuccess ...那么如何解决呢?
您必须分配该对象,否则它将保持为空。您可以在CustomVolley类中添加设置器。例如
public void setOnCallbackResponse(OnCallbackResponse l) {
OnCallbackResponse = l;
}
在您的活动中执行以下操作:
customVolley.setOnCallbackResponse(this);
this
作为的参数setOnCallbackResponse
,因为GeneralBusinessActivity
在您的情况下正在实现接口
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句