Return the JSONObject response in method - android

I want to return the result or response of JSONObject But response is not able to return. HOw to do this?
private String requestJSON(String stringURI) {
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, stringURI, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Here I want to return this response at the end of this method
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(objectRequest);
return response.toString;
}

Related

Volley -JsonArrayRequest Displaying Error

here is my code, whenever i try to make the Response to convert to toString() i get the error
private void fetchStoreItems() {
String url = "https://newsapi.org/v1/articles?source=techcrunch&apiKey=47bdfe44632849b4bdf0c2a9035a68e7";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
url, new com.android.volley.Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
VolleyLog.d("ecardCalled: ", response.toString());
}
},new com.android.volley.Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("ecardCalled: ", error.toString());
}
});
MyApplication.getInstance().addToRequestQueue(jsonArrayRequest);
}
what am i not actually doing Right?
You have to provide json params value if you have any otherwise set it to null
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
url,null, new com.android.volley.Response.Listener<JSONArray>() {
#Override
....
....
...
//other code
use this code instead of yours:
private void fetchStoreItems() {
String url = "https://newsapi.org/v1/articles?source=techcrunch&apiKey=47bdfe44632849b4bdf0c2a9035a68e7";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
VolleyLog.d("ecardCalled: ", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("ecardCalled: ", error.toString());
}
});
MyApplication.getInstance().addToRequestQueue(jsonArrayRequest);
}

Multiple object request using Volley Android

I want to call API Using Volley. There is an Multiple object Request So i don't Know Proper way. I was tried to code as below.But it does not give me Response.So can Anyone help me???
MainActivity
public void getJsonResponsePost(){
JSONObject jsonData = new JSONObject();
JSONObject json = new JSONObject();
/*{"data":{"lang_type":"1","keyword":"","latitude":23.022499999999997,"longitude":72.57139833333333,"category":6}}*/
try {
jsonData.put("data",json);
json.put("lang_type","1");
json.put("keyword","");
json.put("latitude",23.022499999999997);
json.put("longitude",72.57139833333333);
json.put("category",6);
Log.d("TAG",jsonData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
Log.d("String Response :",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(" Error getting :",error.toString());
}
});
jsonObjectRequest.setTag(REQ_TAG);
requestQueue.add(jsonObjectRequest);
}
I get the following response
StringĀ ResponseĀ :: {"status":"0","message":"Please pass the language type."}
Can you try this?
try {
json.put("lang_type","1");
json.put("keyword","");
json.put("latitude",23.022499999999997);
json.put("longitude",72.57139833333333);
json.put("category",6);
jsonData.put("data",json);
Log.d("TAG",jsonData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonData, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
Log.d("String Response :",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(" Error getting :",error.toString());
}
});

What is the best helper method for volley to make get and post requests?

I have got the following helper method to deal with volley.
public interface OnFinishListener { public void onFinish( JSONObject o ); }
public class VolleyHelper {
public JSONObject get(String url, OnFinishListener ofl ) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
ofl.onFinish( jsonObject );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//return jsonerror
}
});
addToRequestQueue(request);
}
}
Is there any other best practice helper method which is better than the above code?

Return JSON from custom VolleyCallback interface to calling method

I have the method below: What it does is that the method userSignIn is called from another activity and returns a JsonObject,since my volley implementation does its calls asynchronously I have implemented callback interface that fetches the result fron the OnResponce method. However the difficulty am facing is returning the JSONObject to the calling Activity.
#Override
public JSONObject userSignIn(String user, String pass,String version, String authType, String URL) throws Exception {
urlBuilder = new StringBuilder(URL);
urlBuilder.append("?uname=" + user);
urlBuilder.append("&passwd=" + pass);
urlBuilder.append("&ver=" + version);
URI=urlBuilder.toString();
VolleyLoginExecute(new VolleyCallback() {
#Override
public JSONObject onSuccess(JSONObject result) {
responce = result;
return responce;
}
});
return responce;
}
public interface VolleyCallback{
JSONObject onSuccess(JSONObject result);
}
public JSONObject VolleyLoginExecute(final VolleyCallback callback) {
JsonObjectRequest LoginReq = new JsonObjectRequest(Request.Method.GET,URI, null,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null) {
callback.onSuccess(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
public Priority getPriority() {
return priority;
}
};
LoginReq.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Acme_Application.getInstance().addToRequestQueue(LoginReq, tag_login_req);
return responce;
}
I have tried this as well to return the JsonObject but it does not work as well
#Override
public JSONObject userSignIn(String user, String pass,String version, String authType, String URL) throws Exception {
urlBuilder = new StringBuilder(URL);
urlBuilder.append("?uname=" + user);
urlBuilder.append("&passwd=" + pass);
urlBuilder.append("&ver=" + version);
URI=urlBuilder.toString();
return VolleyLoginExecute(new VolleyCallback() {
#Override
public JSONObject onSuccess(JSONObject result) {
responce = result;
return responce;
}
});
}
How can I return the JsonObject to the calling activity successfully
#Override
public void userSignIn(final VolleyCallback volleyCallback,String user, String pass,String version, String authType, String URL) throws Exception {
urlBuilder = new StringBuilder(URL);
urlBuilder.append("?uname=" + user);
urlBuilder.append("&passwd=" + pass);
urlBuilder.append("&ver=" + version);
URI=urlBuilder.toString();
VolleyLoginExecute(new VolleyCallback() {
#Override
public void onSuccess(JSONObject result) {
volleyCallback.onSuccess(result);
}
});
} public interface VolleyCallback{
void onSuccess(JSONObject result);
} public void VolleyLoginExecute(final VolleyCallback callback) {
JsonObjectRequest LoginReq = new JsonObjectRequest(Request.Method.GET,URI, null,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null) {
callback.onSuccess(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
public Priority getPriority() {
return priority;
}
};
LoginReq.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Acme_Application.getInstance().addToRequestQueue(LoginReq, tag_login_req);
}

Android Volley: how to make json request without returned object?

Now I'm doing
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, uri, json,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
// do action
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//manage error
}
}
);
My servlet uses Jersey as JAX-RS.
The resource called by the uri passed as parameter does not produce any json object. If I do this way, the error callback is called even if the json object sent with POST is correctly used on server.
If I return a json with fake data then the response callback is called, but I don't need to send back an object (wasting the user's data bandwidth). I'd like to do the normale response action if the code of response is OK or 200.
How should I do?
You can override the parseNetworkResponse method of JsonObjectRequest so that it accepts null responses:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, uri, json,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
// do action
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//manage error
}
}
) {
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data,
"UTF-8"
);
if (json.length() == 0) {
return Response.success(
null,
HttpHeaderParser.parseCacheHeaders(response)
);
}
else {
return super.parseNetworkResponse(response);
}
}
catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
};

Categories

Resources