我不知道这是否解决以下问题的正确办法:
我必须记录一些GPS数据并将其存储在JSON中。此数据将被发送到服务器以存储在数据库中。服务器能够处理任意长度的JSON数组。有关守则是:
public void onLocationChanged(final Location location) {
try{
JSONObject temp = new JSONObject();
temp.put("trackerid", prefs.getString("trackerid", "Some ID"));
temp.put("latitude", location.getLatitude());
temp.put("longitude", location.getLongitude());
Calendar time = Calendar.getInstance();
Date currentLocalTime = time.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-d hh:m:ss", Locale.ENGLISH);
temp.put("timestamp",sdf.format(currentLocalTime));
arrJ.put(temp);
}
catch (JSONException e){
log("Not able to format JSON" + ": "+ e.toString());
}
StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Code that verifies if the request is successfull and removes only the sent objects from the JSONArray.
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error){
//Code that Handles the error.
}
}){
@Override
protected Map<String, String> getParams(){
Map<String, String> params = new HashMap<>();
try {
params.put("data", json.put("data", arrJ).toString());
}catch (JSONException e){
e.printStackTrace();
}
return params;
}
};
queue.add(sr);
}
我面临的问题如下:一旦GPSData被记录在JSONArray中,它就会被网络(Volley)请求线程获取并处理。现在,由于我不知道请求需要多长时间,所以我需要能够在getParams()
函数中获取onResponse()
函数中的已发送参数,以便能够从JSONArray中只删除已发送的对象以避免重复。
我不知道这是否正确的实施。如果有一个更好的方法,我肯定是开放的,将其纳入应用程序。
发布于 2017-06-23 08:42:56
您可以使用此自定义请求,
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* @author Krish
*/
public class CustomRequest {
private Response.Listener<String> mOriginalListner;
private String requestData;
private StringRequest request;
public CustomRequest(int method, String json, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
this.requestData = json;
this.mOriginalListner = listener;
init(method, url, mListener, errorListener);
}
private Response.Listener<String> mListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mOriginalListner.onResponse(requestData);
}
};
private void init(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
this.request = new StringRequest(method, url, listener, errorListener) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
try {
params.put("data", requestData);
} catch (Exception e) {
e.printStackTrace();
}
return params;
}
};
}
public StringRequest build() {
return request;
}
}
您可以使用响应来删除send对象。
https://stackoverflow.com/questions/44715694
复制相似问题