Android: How to Return Async JSONobject from Method Using Volley

Android: How to return async JSONObject from method using Volley?

For your comment

I think that async is provided by Volley automatically. So i need to
know how to get JSON data into the first snippet

IMO, instead of your first snippet, you can try the following way (of course, you can replace JSONArray request by JSONObject request):

VolleyResponseListener listener = new VolleyResponseListener() {
@Override
public void onError(String message) {
// do something...
}

@Override
public void onResponse(Object response) {
// do something...
}
};

makeJsonArrayRequest(context, Request.Method.POST, url, requestBody, listener);

Body of makeJsonArrayRequest can be as the following:

    public void makeJsonArrayRequest(Context context, int method, String url, String requestBody, final VolleyResponseListener listener) {
JSONObject jsonRequest = null;
try {
...
if (requestBody != null) {
jsonRequest = new JSONObject(requestBody);
}
...
} catch (JSONException e) {
e.printStackTrace();
}

JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(method, url, jsonRequest, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray jsonArray) {
listener.onResponse(jsonArray);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
listener.onError(error.toString());
}
});

// Access the RequestQueue through singleton class.
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
}

VolleyResponseListener interface as the following:

public interface VolleyResponseListener {
void onError(String message);

void onResponse(Object response);
}

Android : how to return JSONObject from Volley OnRequest StringRequest method

If the String response from your StringRequest always has the following format:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">........</string>

in which ........ is the JSONObject you want to get, I suggest that you process the String reponse like the following way:

...
String jsonString = stringResponse;

jsonString = jsonString.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>"," ");
jsonString = jsonString.replace("<string xmlns=\"tempuri.org/\">"," ");
jsonString = jsonString.replace("</string>"," ");
try {
JSONObject jsonObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
...

Back to your code, data of course NULL because JSONObject json = JSONObject(data); called before onResponse inside the Request called. I suggest that you refer to my answer at the following question for your issue:

Android: How to return async JSONObject from method using Volley?

Hope this helps!



Related Topics



Leave a reply



Submit