我有一些方法可以从Google App脚本接收数据,但是为所有方法放置相同的代码要花一些时间。
例如,这是我的checkIn方法,但是我需要创建checkOut方法或UpdateReservation来从google中的javascript接收实际功能。有一种方法可以缩短此Volley Stringrequestcode。
或者我至少可以在firebase中使用这种编码或功能,并且容易得多吗?
private void checkIn() {
final RequestQueue requestQueue = Volley.newRequestQueue(Reservations.this);
final StringRequest stringRequest = new StringRequest(Request.Method.POST, "url",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
) {
@Override
protected Map<String, String> getParams() {
Map<String, String> parmas = new HashMap<>();
//here we pass params
parmas.put("action","checkIn");
return parmas;
}
};
int socketTimeOut = 50000;// u can change this .. here it is 50 seconds
RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(retryPolicy);
requestQueue.add(stringRequest);
}
});
}
答案 0 :(得分:0)
基本上,您需要一种更紧凑的方式来编写代码。我说得对吗?
您可以使用lambdas以更紧凑的方式编写侦听器:
StringRequest request = new StringRequest(Request.Method.POST, "url",
(response) -> {
//Handle response
},
(error) -> {
//Handle error
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> parmas = new HashMap<>();
//here we pass params
parmas.put("action","checkIn");
return parmas;
}
};
如果每种情况的getParams(...)
方法仅向参数映射添加一个action
键,则可以创建一个扩展StringRequest
并具有此功能的类。
public class CustomStringRequest extends StringRequest {
private String action;
public CustomStringRequest(int method, String url, String action, Response.Listener listener, Response.ErrorListener el) {
super(method, url, listener, el);
this.action = action;
}
@Override
protected Map<String, String> getParams() {
Map<String, String> parmas = new HashMap<>();
//here we pass params
parmas.put("action", action);
return parmas;
}
}
然后在每种方法中,您可以按以下方式编写请求:
request = new CustomStringRequest(Request.Method.POST, "url", "checkIn",
(response) -> {
//Handle response
},
(error) -> {
//Handle error
});
请注意,“ checkIn”类型的操作已传递到CustomStringRequest
构造函数中!
所以最后你得到了类似的东西
private void checkIn() {
final RequestQueue requestQueue = Volley.newRequestQueue(Reservations.this);
final StringRequest stringRequest = new CustomStringRequest(Request.Method.POST, "url", "checkIn",
(response) -> {
//Handle response
},
(error) -> {
//Handle error
});
int socketTimeOut = 50000;// u can change this .. here it is 50 seconds
RetryPolicy retryPolicy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(retryPolicy);
requestQueue.add(stringRequest);
}