i need to pass the response string by assigning value to the string data to another method out side the OnResponse() scpoe so that i can return a JSONObject from it by calling that method but it always returns null
all i need is to get JSONObject from Volley stringrequest as the response is a xml "
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">........</string>
Here is my code
static String data;
private void driverByIdStringRequest(int ID,final Context context){
RequestQueue queue = VolleySingleton.getInstance(context.getApplicationContext()).getRequestQueue();
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url+ID,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
response = response.replaceAll("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
response = response.replaceAll("<string xmlns=\"http://tempuri.org/\">", "");
response = response.replaceAll("</string>", "");
String data = response.substring(40);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error : ", error.toString());
}
});
VolleySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
public JSONObject GetDriverById(int ID,Context context){
driverByIdStringRequest(ID, context);
JSONObject json = JSONObject(data);
return json;
}
The best maintainable way to do it is first to parse you XML with a Parser.
Just follow this tutorial on the official doc.
Once you got your string you just have to do
JSONObject mainObject = new JSONObject(Your_Sring_data);
(Android studio will prompt you to put the correct try/catch around the JSON creation.)
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.