Issue
I want to access an online API through an android application. For this purpose I have written easy to access functions to send requests via the android Volley package. However the app immediately displays 0s when I try to assign a value, that I have recieved through sending a request, to a TextView. I realize that this probably is because the function handles the Object as "null" because the response has not yet arrived and that I need to use AsyncTasks to handle this properly but the Developer Guide from Android Studio didn't really help me too much because, to be absolutely 100% honest with you, I'm not a software engineer and I'm absolutely lost at this point.
Here's some code on how I access the API:
org.json.JSONObject makeRequest(String URL, String method, String[] headers){
int reqType;
switch(method.toUpperCase()){
case "GET":
reqType = Request.Method.GET;
break;
case "DELETE":
reqType = Request.Method.DELETE;
break;
default:
return null;
}
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>(){
@Override
public void onResponse(JSONObject Response){
result = Response;
}
};
Response.ErrorListener err = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
result = null;
}
};
JsonObjectRequest req = new JsonObjectRequest(reqType, URL, null, listener, err){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put(headers[0], headers[1]);
return params;
}
};
;
rQ_volley.add(req);
return result;
}
And additionally some code on where I access the method above
JSONArray koordTargetArr = rBuild.makeRequestArr("https://nominatim.openstreetmap.org/search?q="+target+"&format=json&polygon=1&addressdetails=1", "get",headersLonLat);
if(koordTargetArr != null) {
JSONObject koordTargetOBJ = koordTargetArr.getJSONObject(0);
koordTarget = koordTargetOBJ.getString("lon").concat(",").concat(koordTargetOBJ.getString("lat"));
}
else return 0;
I would appreciate any help you could give me on things like where I implement the AsyncTask and how I build one. I have experience in the async library in Node.js if that helps at all.
EDIT: This is NOT a duplicate of How to use java.net.URLConnection to fire and handle HTTP requests I already know how to send HTTP Requests, I don't know how to use android AsyncTask, HTTP Requests are NOT the topic of this question.
Solution
Have you considered using Retrofit?
It will handle, construction and deserialization of all your network needs without needing to use AsyncTask + custom utilities functions.
Answered By - Joel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.