I have a Listview with textviews. On a click on the convertview, the method is called:
private void getAmountFromItem() {
String url = "http://192.168.192.200/getAmountFromItem.php?amount_id=" + amountIDTest;
Log.e("URLUZ", "is " + url);
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
feedObj = (JSONObject) feedArray.get(i);
Log.e("COUNTS", " " + feedObj.getString("count"));
textView.setText(feedObj.getString("count") + " count yeah");
textView.invalidate();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
I tried to set the text within "runOnUiThread" or on "textView.post(new Runnable)... but these won't work.. Any suggestions?
You should see this "solution" (best practice for updating ui object from volley)
Related
I have implementing Bing Images Search API with Volley I need to request for the JSONArray values to request all the thumbnail urls. Here is the JSON format for the Bing Image Search:
[
{
"_type":"Images",
"instrumentation":{
},
"readLink":"https:\/\/api.cognitive.microsoft.com\/api\/v7\/images\/search?q=puppies",
"webSearchUrl":"https:\/\/www.bing.com\/images\/search?q=puppies&FORM=OIIARP",
"totalEstimatedMatches":995,
"nextOffset":37,
"value":[
{
"webSearchUrl":"https:\/\/www.bing.com\/images\/search?view=detailv2&FORM=OIIRPO&q=puppies&id=01FB7631BE5F833B1851922E2AE55143A9DDA195&simid=608039673288263152",
"name":"Cute Golden Retriever Puppies Photos ~ Cute Puppies Pictures, Puppy Photos",
"thumbnailUrl":"https:\/\/tse3.mm.bing.net\/th?id=OIP.sa4AFBPcfVJbIx1MEkakmgHaFj&pid=Api",
"datePublished":"2018-02-04T22:46:00.0000000Z",
"contentUrl":"http:\/\/1.bp.blogspot.com\/-NnDHYuLcDbE\/ToJ6Rd6Dl5I\/AAAAAAAACa4\/NzFAKfIV_CQ\/s1600\/golden_retriever_puppies.jpg",
"hostPageUrl":"http:\/\/puppiesphotos.blogspot.com\/2013\/01\/cute-golden-retriever-puppies-photos.html",
"contentSize":"376369 B",
"encodingFormat":"jpeg",
"hostPageDisplayUrl":"puppiesphotos.blogspot.com\/2013\/01\/cute-golden-retriever-puppies...",
"width":1600,
"height":1200,
"thumbnail":{
"width":474,
"height":355
},
"imageInsightsToken":"ccid_sa4AFBPc*mid_01FB7631BE5F833B1851922E2AE55143A9DDA195*simid_608039673288263152*thid_OIP.sa4AFBPcfVJbIx1MEkakmgHaFj",
"insightsMetadata":{
"recipeSourcesCount":0,
"bestRepresentativeQuery":{
"text":"Cute Golden Retriever Puppies",
"displayText":"Cute Golden Retriever Puppies",
"webSearchUrl":"https:\/\/www.bing.com\/images\/search?q=Cute+Golden+Retriever+Puppies&id=01FB7631BE5F833B1851922E2AE55143A9DDA195&FORM=IDBQDM"
},
"pagesIncludingCount":1238,
"availableSizesCount":240
},
"imageId":"01FB7631BE5F833B1851922E2AE55143A9DDA195",
"accentColor":"AA6F21"
}
]
}
]
This is my Volley Request for JSON Array.
private void requestedTrendingImages(String url) {
Log.d("Query URL: ", url);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject images = response.getJSONObject(i);
jsonResponse = images.getString("thumbnailUrl");
Log.d(TAG, jsonResponse);
}
Log.d(TAG, jsonResponse);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
HolaApp.getInstance().addToRequestQueue(jsonArrayRequest);
}
My String URL is correct I am new to Volley could anyone help me with parsing JSON Array.
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray jsonArray = response.getJSONArray("value");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject Image = (JSONObject) jsonArray.get(i);
urls = Image.getString("thumbnailUrl");
Log.d(TAG, "onResponse: "+urls);
}
Log.d(TAG, jsonResponse);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
try this
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray values = response.getJSONArray("value")
for (int i = 0; i < values.length(); i++) {
String url = values.getJSONObject(i).getString("thumbnailUrl");
//do something with the url
Log.d(TAG, url);
}
Log.d(TAG, jsonResponse);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Well I found out the answer final which worked for me. I should have used JSONObject instead of JSONArray!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newRequestSearchImages(Constants.BING_ENDPOINT_SEARCH + Constants.QUERY + "puppies" + Constants.API_KEY);
}
private void newRequestSearchImages(String url){
JsonObjectRequest jsonObjectRequest = 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("value");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
jsonResponse = object.getString("thumbnailUrl");
Log.d(TAG, jsonResponse);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.getMessage());
}
});
HolaApp.getInstance().addToRequestQueue(jsonObjectRequest);
}
/**
* Method to make json array request where response starts with [
* Requesting data from url
* */
private String urlJsonArry_local = "http://www.endorecord.in/endorecord/hospitaladmin/Api/device_hospitals.php?deviceid=";
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry_local +androidID,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String name = person.getString("hospitalid");
String email = person.getString("hospital_name");
/*JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
*/
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
//jsonResponse += "Home: " + home + "\n\n";
//jsonResponse += "Mobile: " + mobile + "\n\n\n";
}
Toast.makeText(getApplicationContext(), jsonResponse, Toast.LENGTH_LONG).show();
//txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
you should be passing your url in the request "http://www.google.com"+androidID not this. And the Url urlJsonArry_local that you have mentioned above returns json object response not jsonArray, Your code and Json reponse are completely irrelavant
for the Json respone in above url
private String urlJsonArry_local = "http://www.endorecord.in/endorecord/hospitaladmin/Api/device_hospitals.php?deviceid=";
RequestQueue queue = MyVolley.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,urlJsonArry_local,null/* paramateres passed here*/,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject jObject = response;
String status = jObject.getString("status");
JSONArray hospitalArray = jObject.getJSONArray("hospital");
//your for loop to parse hospital array here
hideProgressDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
});
queue.add(jsObjRequest);
Ways to implement volley json response cache.I tried the following way to get response from volley.i get the response correctly.I dont know how to store these json values into volley cache
StringRequest strReq = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("mainresp$$$"+response);
Log.d("Volley Request Success", response.toString());
result=response;
callback.onSuccess(result);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley request Error",
"Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
Together with my comments, you have already read my answer at the following question:
Android Setup Volley to use from Cache
I have just tested with POST request, as the following code:
CacheRequest cacheRequest = new CacheRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
// Check if it is JSONObject or JSONArray
Object json = new JSONTokener(jsonString).nextValue();
JSONObject jsonObject = new JSONObject();
if (json instanceof JSONObject) {
jsonObject = (JSONObject) json;
} else if (json instanceof JSONArray) {
jsonObject.put("success", json);
} else {
String message = "{\"error\":\"Unknown Error\",\"code\":\"failed\"}";
jsonObject = new JSONObject(message);
}
textView.setText(jsonObject.toString(5));
} catch (UnsupportedEncodingException | JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
});
My sample Asp.Net Web API code as the following:
// POST api/<controller>
public IHttpActionResult Post()
{
string jsonString = "[" +
"{" +
"name: \"Person 1\"," +
"age: 30," +
"type: \"POST\"," +
"}," +
"{" +
"name: \"Person 2\"," +
"age: 20," +
"type: \"POST\"," +
"}," +
"{" +
"name: \"Person 3\"," +
"age: 40," +
"type: \"POST\"," +
"}" +
"]";
JArray jsonObj = JArray.Parse(jsonString);
return Ok(jsonObj);
}
Here is the result screenshot
I am having problem with volley library. I dont understand where i am getting all the values from in the application even the internet is not accessible and the data is not available in the api itself. I tried to clear the cache but nothing is working. Any suggestion would be appreciated. Thanks
private void makeJsonObjReq() {
//Log.e("makeJsonobjReq method", "inside");
pinfo = new PostsInfo();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
Const.URL_JSON_ARRAY, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray jArray;
Log.e(TAG +"", " rrr "+ response.toString());
try {
Log.e(TAG, "" + response.getInt("count") + " " + response.getInt("pages") + " " + response.getInt("page"));
for (int i = response.getInt("page"); i <= response.getInt("pages"); i++) {
jArray = response.getJSONArray("results");
for (int j = 0; j < response.getInt("count"); j++) {
try {
a_fetch_data.open();
JSONObject json = jArray.getJSONObject(i);
Log.e(TAG +" no of count in array", "i = "+ json.getString("id"));
//jsonObjectValue(json);
}
catch (JSONException e) {
e.printStackTrace();
}
}
Log.e(TAG, "Array "+ " Completed ");
}
}
catch (JSONException e1) {
e1.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
/*Adding request to request queue*/
ApplicationController.getInstance().addToRequestQueue(jsonObjReq,
"jobj_req");
ApplicationController.getInstance().getRequestQueue().getCache().remove("jobj_req");
}
api :http://bumpintomums.com.au/wp-content/themes/bumpii/API/get_data.php
The problem is, this method returns a response even though i am not connected to internet and i have not instantiated any cache work here.
I have followed this tutorial.
The author directly uses the data in the callback by setting the textview within the callback. What I would like to do is populate an array with the response I'm getting from my request, and then be able to use that array elsewhere (as the response listener is an anonymous inner class, I can't figure out how to get data from it; any attempt to assign to an array inside the listener has proved fruitless.
Thanks, please bear with me as I'm still a beginner.
The listener:
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String name = person.getString("name");
String email = person.getString("email");
JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
jsonResponse += "Home: " + home + "\n\n";
jsonResponse += "Mobile: " + mobile + "\n\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
EDIT: The code below outlines the problem I'm having. I'm aware this is probably due to misunderstanding or misapplication on my part but still.
private void makeJsonArrayRequest(String url){
//ONLY WAY TO ACCESS INSIDE LISTENER IS TO MAKE FINAL
final ArrayList<String> string = new ArrayList<>();
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(
url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject field = (JSONObject) response.get(i);
string.add(i, field.getString("title"));
//THIS PRINTS OUT ALL MY TITLES CORRECTLY, SHOWING THAT
//THE STRINGS ARRAY IS POPULATED IN THIS SCOPE
Log.d(AppController.TAG, string.get(i));
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(AppController.TAG, "Error: " + error.getMessage());
Toast.makeText(context,
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
}
);
AppController.getInstance().addToRequestQueue(req);
//THIS CAUSES AN OUT OF BOUNDS EXCEPTION, AS IT THINKS THE ARRAY HAS NOT BEEN POPULATED
Log.d(AppController.TAG, string.get(3));
}
I think the problem is using variable string as a copy of actual string inside OnResponse(..).
Try adding static to this variable :
final static ArrayList<String> string = new ArrayList<>();