I am familiar with Volley and creating a Singleton class, and adding requests to the queue. However, I wish to increase the modularity of volley and simply call all requests through method call to another class instead. I have setup the present action as basis for the common GET request:
public Object getRequest(String params) {
final JSONObject getRequestReturn = new JSONObject();
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET,
VolleySingleton.prefixURL, ((String) null),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
getRequestReturn = response;
Log.v("GET Request value", response.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("GET Request Error", error.toString());
}
});
mRequestQueue.add(getRequest);
return getRequestReturn;
}
However, I have a the perplexing catch 22 error on the assignment of response at:
getRequestReturn = response;
The error notes that getRequestReturn must be declared final to allow for use within the inner class, but upon assigning final, another error appears noting that you cannot assign a value to a final variable.
How can this method be handled?
Declare JSONObject as global and initialize in same place like this.
JSONObject getRequestReturn ;
getRequestReturn = new JSONObject();
public Object getRequest(String params) {
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET,
VolleySingleton.prefixURL, ((String) null),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
Log.v("GET Request value", response.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("GET Request Error", error.toString());
}
});
mRequestQueue.add(getRequest);
return new JSONObject();
}
U can't get response when u return!Volley request is async!
I use EventBus and I do it like this :
When I need to get data from web , i add a request like this.
Then when i get response from web ,I use EventBus to post a event.
I get the event and update my page.
Or U can try the RxAndroid.
Related
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
I'm trying to retrieve a token from a JSON response. I've successfully managed to get a response, but I don't know how to retrieve the token.
Here's my code
private void TmdbAuth() {
final String TokenUrl = "https://api.themoviedb.org/3/authentication/token/new?api_key=<<api key goes here>>";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
TokenUrl,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.i("jjj", response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
);
requestQueue.add(jsonObjectRequest);
}
and the response of this json
{"success":true,"expires_at":"2019-04-01 10:49:44 UTC","request_token":"request token goes here"}
How do I retrieve only the request_token
Try this #tony
JsonObject object = new JsonObject(response); //obtained response from the server.
String request_token = object.getString("request_token");
Log.e("request_token",request_token); //Just for checking in the logcat.
You can access token String this way
String token = response.optString("request_token");
You can try like this
try{
Log.i("jjj", response.toString());
String requestToken = response.getString("request_token");
}
catch (Exception e) {
e.printStackTrace();
}
I have Authentication class which have method Auth with 2 arguments.
after calling that method a volley request generated and response catch through other function because of aSync. that object is a Static object and accessible in other class but that shows null always after making object or initializing it onCreate of activity.
Let check my Authenticate class:
public class Authenticate {
private static final String URL = "http://allskkc/zaigham/idsrs_authentication.php";
public static JSONObject finalresult;
public Authenticate() {
}
public static void Auth(String IEMI, String PIN) throws TimeoutException {
final JSONObject params = new JSONObject();
finalresult = new JSONObject();
RequestQueue queue = Volley.newRequestQueue(Splash.context);
try {
params.put("iemi", IEMI);
params.put("pin", PIN);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("params to server", params.toString());
JsonObjectRequest jsOBJRequest = new JsonObjectRequest
(Request.Method.POST, URL, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("response from server", response.toString());
ftn(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Response error",error.toString());
}
});
queue.add(jsOBJRequest);
}
public static void ftn(JSONObject jsonObject) {
finalresult = jsonObject;
Log.e("as", "Response in ftn() = " + finalresult.toString());
}
}
final finalresult have value when I call that Auth() method but in my Login class it shows {}
let check my method call:
try {
Authenticate.Auth("358607051299527","1122");
} catch (TimeoutException e) {
e.printStackTrace();
}
Log.e("as","Prefrences Saved");
Log.e("as","My final result = "+Authenticate.finalresult.toString());
I attached my Log.e Image that may help more to understand.
You can see in your logs that application tries to get the result of request before request is done. Network request is asynchronous, it is done on background thread.
You should get the result after request is finished in some sort of callback.
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.
I am using volley library to get data from an api in JSON format, and it works like a charm. I ask for JSON file, i get a response, i parse that respons and populte the views in activity.
Now, i have a button to share the data using Intetnt.ACTION_SEND and putExtra(Intent.EXTRA_TEXT) that takes string as the 2nd parameter.
The problem is, i make a string variable and append data in that string variable inside volley on response method. but as volley makes a new thread for getting data from api the string is not updated and Intetnt.EXTRA_TEXT sends an empty string.
I want to ask, if there is anything similer to onPostExecute method for volley? where i can set the data to some variables after the thread is done processing. or any alternate methods to do the same.
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.GET, bookSearchString, null,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray bookArray = response
.getJSONArray("items");
JSONObject bookObject = bookArray.getJSONObject(0);
try {
bookSelfLink = bookObject.getString("selfLink");
JsonObjectRequest newJsObjRequest = new JsonObjectRequest(
Request.Method.GET, bookSelfLink, null,
new Response.Listener<JSONObject>() {
public void onResponse(
JSONObject response) {
try {
JSONObject newBookObject = response
.getJSONObject("volumeInfo");
try {
dBookPages.setText("Pages - "
+ newBookObject
.getString("pageCount"));
eMailText = eMailText + newBookObject
.getString("pageCount"));
} catch (JSONException jse) {
dBookPages
.setText("Pages not found");
jse.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(
VolleyError error) {
// TODO Auto-generated method
// stub
}
});
AppController.getInstance().addToRequestQueue(
newJsObjRequest, tag_json_obj);
} catch (JSONException jse) {
jse.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
AppController.getInstance().addToRequestQueue(jsObjRequest,
tag_json_obj);
from the Volley v1.0.0 Documentation:
public boolean hasHadResponseDelivered()
Returns true if this request has had a response delivered for it.
I hope that this answer would help someone with the same question.
There were 2 work around for the record.
1) make network call on button click -> wait for response -> fire intent inside onResponse with bundled data.
2) pass url as string in bundle -> call intent for new activity -> make network request pars data.