Android Volley Request Response not in order - android

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.

Related

How do I solve Error org.json.jsonexception.No value fo login

I'm trying to login a registered user using their email and password from the registration credentials. How do I place value for login?
This is for a new xamp server. ,
private void Login( final String email, final String password) {
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("login");
if (success.equals("1")){
for (int i = 0; i < jsonArray.length(); i++ ){
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name").trim();
String email = object.getString("email").trim();
Toast.makeText(Login.this,
"Success login. \nYour Name : "
+name+"\nYour Email : "
+email, Toast.LENGTH_SHORT)
.show();
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "Error " +e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "Error " +error.toString(), Toast.LENGTH_SHORT).show();
}
})
}

JSON parsing problem with Volley in Android?

This project used to work successfully before. After we changed URL from web service that don't parse data. We changed URL bus/search instead of bus.
This is where I send request and it run successfully with new URL. But this state is working and show this fault.
catch (JSONException e) {
Log.e("search" + owner + "VoyagesErr1", e.toString());
e.printStackTrace();
}
error: e: "org.json.JSONException:No value for status
Voyage.java
private void sendRequest(final String owner, final Map<String, String> header) {
//url = "http://12.1.1.12:1337/";
StringRequest stringRequest = new StringRequest(Request.Method.POST, MyConstants.URL + owner,
new Response.Listener<String>() {
#Override
// servisten 200 olarak bir veri alındığında onResponse içine düşüyor.
public void onResponse(String response) {
// Log.e("AAAA" + owner, response);
try {
JSONObject object = new JSONObject(response);
if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_NOTAVAILABLE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_NOTAVAILABLE);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {
JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
if (has_return) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAİLURE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
}
} catch (JSONException e) {
Log.e("search" + owner + "VoyagesErr1", e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("AAAA" + owner, String.valueOf(error.getCause()));
sendVoyagesErrorBroadcast(owner, getErrorType(error));
}
It don't receive in this class.
MyBaseVoyageFragment.java
String broadcastTAG = BROADCAST_TAG + owner + String.valueOf(direction);
if (intent != null) { // put the receiving data on intent
Log.e("received", intent.getAction()); // succesfull action
String intentAction = intent.getAction();
if (intentAction.equals(broadcastTAG)) {
parseIntentDataAndLoadVoyagesAdapter = new ParseIntentDataAndLoadVoyagesAdapter(intent);
parseIntentDataAndLoadVoyagesAdapter.execute(""); // asenkron görevi çalıştır.
//loadVoyagesToAdapter();
} else if (intentAction.equals(BROADCAST_TAG + owner + "Error")) {
showLoadingDialog(false);
setErrorView(intent.getIntExtra("data", 0));
}
}

Volley JSON Exception with Bing Search API

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);
}

I am trying to get the value using JSON in android, Below is my code, It shows null pointer exception and error during request queue

/**
* 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);

Android JSON request populating array

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<>();

Categories

Resources