Could not get response using volley lib - android

I got stuck with Volley library, any one please help me out.
The question is, I'm using Volley library for API call, it works when I call in a traditional method. I tried to use Volley library for better response but I'm not getting any response, some times I get the response but many times it fails. My snippet is:
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
parseJSON(response);
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new VolleySearchResultAdapter(searchResults, mImageLoader);
lstView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,error.getMessage());
}
});
mRequestQueue.add(jr);
And how do I do pagination using this library?

Related

Not able to fetch JSON data [using volley Library] in Android

The jason array request code goes like this:
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET,url, (JSONArray) null , new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Log.d("Response:", String.valueOf(response.getJSONObject(0)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response not recieved", Toast.LENGTH_SHORT).show();
}
});
And I've used a singleton instance of a request queue, to fetch the data,
AppController.getInstance(context.getApplicationContext()).addToRequestQueue(arrayRequest);
I'm using an api service that supplies a bunch of questions (The api generates a url, which returns a collection of JSON Objects, An Array (Just try and Open the url link, the json array will be seen)
But when I run the app, the request is not even getting a response,the progam flow is going into the error listner block.
Can someone explain this behaviour? Is it because the JSON array supplied by the url, has nested arrays? Why?
I tried reading and anlyzing other questions here, which might have the same issue, But i found nothing.
You want to just change JsonArrayRequest to JsonObjectRequest:
Please copy and paste below code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String category = jsonObject.getString("category");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
// hide the progress dialog
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, "TAG");
Follow this link for learn other request: Androidhive

How can I throw a custom exception from Volley's onResponse and onErrorResponse methods

I have code that accesses an API which returns a series of geopoints for plotting a cycling route. As such, I first fetch the JSON object, then translate it to plottable points. I have an APIGenericException for all Exceptions relating to this API and I want to throw an APiRequestException (Which is a subclass of APIGenericException), if the request to the API is unsuccessful. I cannot figure out how to throw this as the onErrorResponse() method by Volley does not throw an exception. In addition to this, convertResponseToWayPoints also throws an exception, but I'm not sure how to pass that up to the onResponse and onto the requestRouteFromAPI method.
public void requestRouteFromAPI(Context mainActivityContext, final String url) throws APIGenericException {
RequestQueue queue = Volley.newRequestQueue(mainActivityContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
convertResponseToWayPoints(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error){
// TODO: Handle error
Log.e("ERROR", "Error occurred ", error);
throw new APiRequestException(url);
}
}); queue.add(jsonObjectRequest);}
I think I may have a solution, but I'm not 100% sure based on not understanding how Volley's request operates. If the request is synchronous, would this be a way of approaching the issue? By adding a JSONObject that is assigned and then handling it outside the method.
private JSONObject APIrequestResponse;
public void getRoute(Context mainActivityContext) throws CycleStreetsException {
requestRouteFromCycleStreets(mainActivityContext, getAPIURL());
if(APIrequestResponse == null){
throw new CycleStreetsRequestException(getAPIURL());
}
else{
//make routes
}
}
public void requestRouteFromAPI(Context mainActivityContext, final String url) throws APIGenericException {
RequestQueue queue = Volley.newRequestQueue(mainActivityContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
APIrequestResponse = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error){
// TODO: Handle error
Log.e("ERROR", "Error occurred ", error);
APIrequestResponse = null;
}
}); queue.add(jsonObjectRequest);}

Android JSON VOlley

Good Day, I would like to get data from this url, and I have problems with onResponse method implementation:
I have something like this:
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://horoscope-api.herokuapp.com/",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//The Problem is here
JSONArray jsonArray = response.getJSONArray("");
String author = jsonArray.getString(0);
textView.setText(author);
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jsonObjectRequest);
}
I don`t understand how to implement onResponse method correctly, I know that I must to get string from array or object, but data from link make me problems to understand what is it object or array, can you write me how to get author field from this url.
Thank you
Since the response in your link is JSONObject, you only need to do the following inside onResponse:
String author = response.getString("author");
textView.setText(author);
Hope this helps!
The response that you are getting is not a JSONArray but is a JSONObject. You could try the below code and see if you are able to get the author.
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://horoscope-api.herokuapp.com/",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String author = response.get("author");
textView.setText(author);
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jsonObjectRequest);
}
Hope this helps.
The data from link is JSONObject not JSONArray. Call response.getString("author"); to get author string.
try{
String author = response.getString("author");
} catch(JSONException e) {
e.printStackTrace();
}

Android Volley: Unexpected response code 405

My Android Volley JsonObjectRequest runs into onErrorResponse with the issue:
BasicNetwork.performRequest: Unexpected response code 405 for MY_URL
My URL is valid. I have checked that with a browser and
I get there the expected JSON Object.
So the issue has to be on the client side.
The code 405 means:
Method Not Allowed The method specified in the Request-Line is not
allowed for the resource identified by the Request-URI. The response
MUST include an Allow header containing a list of valid methods for
the requested resource.
my code for JsonObjectRequest:
JsonObjectRequest jsonReq;
jsonReq = new JsonObjectRequest(URL_FEED, new JSONObject(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.v("ERROR:%n %s", error.getMessage());
}
});
// Adding request to volley request queue
NetworkController.getInstance().addToRequestQueue(jsonReq);
Do I have to add some information to the header? And if what for information?
The issue was that the request was set to POST by default.
The solution that worked for me:
JsonObjectRequest jsonReq = new JsonObjectRequest
(Request.Method.GET, URL_FEED, null, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
Log.d("Server", "Läuft");
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Log.d("Server","onErrorResponse");
}
});
NetworkController.getInstance().addToRequestQueue(jsonReq);
Use GET Method instead of POST it has worked for me.
I had the same issue, and I found out that my API URL was wrong.
So, my suggestion is to recheck the API URL.

Retrofit updating class PUT error code 301

Maybe this is a silly question but I've been stucked on this for a while. I'm implementing some methods for a restApi. I'm using retrofit and I'm trying to update a client information. To do an update I'm using PUT method but I don't know why I'm always getting a 301 CODE and I can't update the information. Here is my code, thank you for everything.
public interface ClientInterface {
#GET("/clients/{clientParam}")
public Client fetchClient(#Path("clientParam") String client);
#GET("/clients/")
public void fetchAllClients(Callback<List<Client>> callback);
#POST("/clients/")
public void newClient(#Body Client client, Callback<Client> callback);
#PUT("/clients/{clientParam}/")
public void updateClient(#Path("clientParam") String cod, #Body Client client,Callback<Client> callback);
}
After that I use the update method in the following way
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Utils.getURLPreferences(DatosClienteActivity.this)).build();
ClientInterface clientRestInter = restAdapter.create(ClientInterface.class);
Client clientsUpdate = new Client();
//Fetch data into clientsUpdate object
clientRestInter.updateClient(codClient, clientsUpdate, new Callback<Client>() {
#Override
public void success(Client client, retrofit.client.Response response) {
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
EDIT:
If I use volley against the same URL it's working perfectly...
RequestQueue queue = Volley.newRequestQueue(this);
final JSONObject jsonObject = new JSONObject();
try {
//Construct jsonObject
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest req = new JsonObjectRequest(Request.Method.PUT, URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
error.printStackTrace();
}
});
queue.add(req);
Finally I solved it.
The problem was that we had two different Client objects and the one that you fetch is the one that you must change and use it to upload with PUT.
I hope that this help somebody.

Categories

Resources