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);
}
Related
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
Issue:
I'm getting data from web-services in JSON format.I am trying to parse "quote" an "Author" but,i am unable to do it.
Here is the data:
{
"success": {
"total": 1
},
"contents": {
"quotes": [
{
"quote": "You are very powerful, provided you know how powerful you are.",
"author": "Yogi Bhajan",
"category": "inspire",
"date": "2018-02-15",
"title": "Inspiring Quote of the day"
}
],
"copyright": "2017-19 theysaidso.com"
}
}
My Java code is :
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("quotes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject getQuote = jsonArray.getJSONObject(i);
String quoteOfTheDay = getQuote.getString("quote");
String author = getQuote.getString("author");
quotesView.append(quoteOfTheDay + author + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
I'm certain that logic for parsing in Java class is incorrect.
Which logic should I use to correct this?
First, you have to get the JSONObject contents before extracting the array quotes.
try {
JSONObject obj = response.getJSONObject("contents"); //first get the JSONObject contents
JSONArray jsonArray = obj.getJSONArray("quotes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject getQuote = jsonArray.getJSONObject(i);
String quoteOfTheDay = getQuote.getString("quote");
String author = getQuote.getString("author");
quotesView.append(quoteOfTheDay + author + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
You missed contents JSONObject.
Copy past below code:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject contentsObject=response.getJSONObject("contents");
JSONArray jsonArray = contentsObject.getJSONArray("quotes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject getQuote = jsonArray.getJSONObject(i);
String quoteOfTheDay = getQuote.getString("quote");
String author = getQuote.getString("author");
quotesView.append(quoteOfTheDay + author + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject contents =
response.getJsonObject("contents");
try {
JSONArray quotes = contents.getJSONArray("quotes");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < quotes.length(); i++) {
JSONObject getQuote = jsonArray.getJSONObject(i);
String quoteOfTheDay = getQuote.getString("quote");
String author = getQuote.getString("author");
quotesView.append(quoteOfTheDay + author + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Try this...
When i run URL in browser its show with updated data but with Volley request URL data not update.
protected void getImagesArray() {
arrayList.clear();
final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCancelable(false);
progressDialog.show();
String url = "https://aditibendi3.000webhostapp.com/test_img/testarray.php";
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressDialog.dismiss();
Log.e(TAG, "onResponse: " + response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = (JSONObject) response.get(i);
String image = jsonObject.getString("image");
model = new Model(image);
arrayList.add(model);
} catch (JSONException e) {
e.printStackTrace();
}
}
gridAdapter = new GridAdapter(MainActivity.this, arrayList);
gridAdapter.notifyDataSetChanged();
gridView.setAdapter(gridAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.e(TAG, "onErrorResponse: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
This is url response
[{"id":"11","image":"11.png"},{"id":"10","image":"10.png"},{"id":"9","image":"9.png"},{"id":"8","image":"8.png"},{"id":"7","image":"7.png"},{"id":"6","image":"6.png"},{"id":"5","image":"5.png"},{"id":"4","image":"4.jpg"},{"id":"3","image":"3.png"},{"id":"2","image":"2.png"},{"id":"1","image":"1.png"}]
and this is volley response
E/MainActivity: onResponse:
[{"id":"9","image":"9.png"},{"id":"8","image":"8.png"},{"id":"7","image":"7.png"},{"id":"6","image":"6.png"},{"id":"5","image":"5.png"},{"id":"4","image":"4.jpg"},{"id":"3","image":"3.png"},{"id":"2","image":"2.png"},{"id":"1","image":"1.png"}]
I have solved this issue by using this line
AppController.getInstance().getRequestQueue().getCache().remove(url);
I am trying to display data received from a json data source. But I am getting an error when I try to parse the data. I am not able to figure out how to solve it.
The json data looks something like this:
click here to view
Here is the function I wrote for parsing :
public void makeJSONRequest() {
JsonArrayRequest req = new JsonArrayRequest(endpoint_final,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// UI
swipeRefreshLayout.setRefreshing(false);
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
JSONObject newsItems = object.getJSONObject("newsItems");
for (int j = 0; j < newsItems.length(); j++) {
titles[j] = newsItems.getString("title");
snips[j] = newsItems.getString("snip");
links[j] = newsItems.getString("link");
}
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Toast.makeText(getActivity(), "JSON Parsing error", Toast.LENGTH_LONG).show();
}
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Error Receiving News", Toast.LENGTH_LONG).show();
}
});
// Adding request to request queue
InitializeVolley.getInstance().addToRequestQueue(req);
}
The error I am getting is :
Error: org.json.JSONException: Value {"newsItems":[{"link":"http://www.srmuniv.ac.in/announcement/special-training-details","snip":"Dear Students,Those who are interested in Placements must follow certain guidelines.You have to clear the tests conducted by CDC and only those...","title":"CDC: Special Training - Updated"}....
Any help will be appreciated.
Thank you!
First of all this json is not an array, it is an object. You should use JsonObjectRequest instead of JsonArrayRequest. You were parsing the json wrongly.
public void makeJSONRequest() {
JsonObjectRequest req = new JsonObjectRequest(endpoint_final,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
// UI
swipeRefreshLayout.setRefreshing(false);
JSONArray newsAr = response.getJsonArray("news");
for (int i = 0; i < newsAr.length(); i++) {
try {
JSONObject newsItem = newsAr.getJSONObject(i);
titles[j] = newsItem.getString("title");
snips[j] = newsItem.getString("snip");
links[j] = newsItem.getString("link");
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Toast.makeText(getActivity(), "JSON Parsing error", Toast.LENGTH_LONG).show();
}
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Error Receiving News", Toast.LENGTH_LONG).show();
}
});
// Adding request to request queue
InitializeVolley.getInstance().addToRequestQueue(req);
}
JSONObject newsItems = object.getJSONObject("newsItems");
replace with
JSONArray newsItems = object.getJSONArray("newsItems");
Instead of writing your own parsing function you could (and definitely should) use a library which does the heavy lifting for you. One example would be Google's Gson library, check it out: https://github.com/google/gson
Parse like :
try {
JSONObject objResponse = new JSONObject(response.toString());
JsonArray arrResponse = objResponse.getJSONArray("newsItems");
for (int i = 0; i < arrResponse.size(); i++) {
JSONObject objItems = arrResponse.get(i);
String link = objItems.getString("link");
}
}catch (Exception e){
e.printStackTrace();
}
JSONObject object =new JSONObject[response];
JSONArray newsItems = object.getJSONArray("newsItems");
for (int j = 0; j < newsItems.length(); j++) {
JsonObject internal=newsItems.getJsonObject(j);
titles[j] = internal.getString("title");
snips[j] = internal.getString("snip");
links[j] = internal.getString("link");
}
Use JSONArray instead of JSONObject class as newsItems is JsonArray.
Try with this:
public void makeJSONRequest() {
JsonArrayRequest req = new JsonArrayRequest(endpoint_final,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// UI
swipeRefreshLayout.setRefreshing(false);
jo = new JSONObject(response);;
JSONArray array = jo.getJSONArray("newsItems");
for (int x = 0; x < array.length(); x++) {
try {
titles[j] = array.getJSONObject(x).optString("title");
snips[j]= array.getJSONObject(x).optString("snip");
links[j] = array.getJSONObject(x).optString("link");
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Toast.makeText(getActivity(), "JSON Parsing error", Toast.LENGTH_LONG).show();
}
}
mAdapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Error Receiving News", Toast.LENGTH_LONG).show();
}
}
);
// Adding request to request queue
InitializeVolley.getInstance().addToRequestQueue(req);
}
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)
I am making multiple Volley StringRequests.
The requestfriendlist method fetches a list of profiles related to "Naruto". The requestimagelink method fetches Images for each profile it got in the previous method result.However the reponse (imagelink) I am getting is not in order from the requestimagelink method is not in order.
For Example -
Request[1,2,3,4]
Response[2,1,4,3] or any other order.
Please help me fix this issue.
Attaching Code Snippet
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomImageAdapter(this, imageList);
listView.setAdapter(adapter);
requestfriendlist("Naruto");
}
private void requestfriendlist (String profilename)
{
String uri = String.format(Config.URL_REQUEST_FRIENDS + "?current_user=%1$s", profilename);
Log.d(TAG + "uri", uri);
StringRequest strReq = new StringRequest(
Request.Method.GET,
uri,
new Response.Listener<String>()
{
#Override
public void onResponse (String response)
{
try
{
JSONObject responseObj = new JSONObject(response);
Log.d(TAG + "friends", response);
JSONArray jResult = responseObj.getJSONArray("req_users");
Toast.makeText(MainActivity.this, jResult.toString(), Toast.LENGTH_SHORT).show();
for(int i = 0; i < jResult.length(); i++)
{
JSONObject jresponse = jResult.getJSONObject(i);
String profile = jresponse.getString("userid");
friendlist.add(profile);
}
for(int i = 0; i < friendlist.size(); i++)
requestimagelink(friendlist.get(i));
}
catch(JSONException e)
{
Log.d(TAG, "error" + e.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error)
{
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
MyApplication.getInstance().addToRequestQueue(strReq);
}
private void requestimagelink (final String profilename)
{
String uri = String.format(Config.URL_REQUEST_IMAGE + "?userid=%1$s", profilename);
Toast.makeText(MainActivity.this, uri, Toast.LENGTH_SHORT).show();
Log.d(TAG, "uri" + uri);
StringRequest strReq = new StringRequest(
Request.Method.GET,
uri,
new Response.Listener<String>()
{
//response from the server
#Override
public void onResponse (String response)
{
try
{
JSONObject responseObj = new JSONObject(response);
((TextView) findViewById(R.id.tvprofilejson)).setText(response);
Log.d(TAG, response);
JSONArray jResult = responseObj.getJSONArray("photos");
for(int i = 0; i < jResult.length(); i++)
{
JSONObject jresponse = jResult.getJSONObject(i);
ImageClass img = new ImageClass();
img.setThumbnailUrl(jresponse.getString("name"));
img.setTitle(profilename);
imageList.add(img);
//imagelinks.add(jresponse.getString("name"));
adapter.notifyDataSetChanged();
}
}
catch(JSONException e)
{
Log.d(TAG, "error" + e.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error)
{
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
Here is how to link your profiles to their images using a hashMap:
ArrayList<String> friendlist = new ArrayList<String>();
/**
Keeps the profiles' images. Later in your arrayAdapter, where you want show thumbnail image, you must
get corresponding ImageClass from of profile with profileName. If the result is null means that the image
is not loaded yet, otherwise you can use the ImageClass object to retreive profile's image.
*/
HashMap<String, ImageClass> profile_img_Hash = new HashMap<String, ImageClass>();
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomImageAdapter(this, imageList);
listView.setAdapter(adapter);
requestfriendlist("Naruto");
}
private void requestfriendlist (String profilename)
{
String uri = String.format(Config.URL_REQUEST_FRIENDS + "?current_user=%1$s", profilename);
Log.d(TAG + "uri", uri);
StringRequest strReq = new StringRequest(
Request.Method.GET,
uri,
new Response.Listener<String>()
{
#Override
public void onResponse (String response)
{
try
{
JSONObject responseObj = new JSONObject(response);
Log.d(TAG + "friends", response);
JSONArray jResult = responseObj.getJSONArray("req_users");
Toast.makeText(MainActivity.this, jResult.toString(), Toast.LENGTH_SHORT).show();
for(int i = 0; i < jResult.length(); i++)
{
JSONObject jresponse = jResult.getJSONObject(i);
String profile = jresponse.getString("userid");
friendlist.add(profile);
}
for(int i = 0; i < friendlist.size(); i++)
requestimagelink(friendlist.get(i));
}
catch(JSONException e)
{
Log.d(TAG, "error" + e.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error)
{
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
MyApplication.getInstance().addToRequestQueue(strReq);
}
private void requestimagelink (final String profilename)
{
//This snippet will prevent re-downloading
if(profile_img_Hash.get(profilename) != null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged(); //Optional. Not neccessary..!
}
});
return; //Because this profile's image is loaded.
}
String uri = String.format(Config.URL_REQUEST_IMAGE + "?userid=%1$s", profilename);
Toast.makeText(MainActivity.this, uri, Toast.LENGTH_SHORT).show();
Log.d(TAG, "uri" + uri);
StringRequest strReq = new StringRequest(
Request.Method.GET,
uri,
new Response.Listener<String>()
{
//response from the server
#Override
public void onResponse (String response)
{
try
{
JSONObject responseObj = new JSONObject(response);
((TextView) findViewById(R.id.tvprofilejson)).setText(response);
Log.d(TAG, response);
JSONArray jResult = responseObj.getJSONArray("photos");
for(int i = 0; i < jResult.length(); i++)
{
JSONObject jresponse = jResult.getJSONObject(i);
ImageClass img = new ImageClass();
img.setThumbnailUrl(jresponse.getString("name"));
img.setTitle(profilename);
imageList.add(img);
//imagelinks.add(jresponse.getString("name"));
//Before notifying the adapter we have to put the img into our hash map.
profile_img_Hash.put(profilename, img);
//Remember, in you getView(..) method of your adapter, you have to get image from
// profile_img_Hash by profileName as key. If the returned result was null do nothing
// If the returned value was not null you can use the ImageClass to provide profile's
// image. :)
adapter.notifyDataSetChanged();
}
}
catch(JSONException e)
{
Log.d(TAG, "error" + e.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error)
{
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
Keep in mind, in your arrayAdapter's getView(...) method you must load profile's image right from profile_img_Hash with profile name as key like this:
ImageClass img = profile_img_Hash.get(profilename);
if(img != null){
//row's imageView.setBitmap(img.getBitmap());
}
Hope this helps.