Show answer every time you hit api in salvo

I need to get an answer 8 times almost (dynamic) based on the size of the list of arrays. So I used the loop.inside for for loop, I use the answer to the volleyball call.

Every time I click on the api, I need to get onResponse.

Below I have placed logcat and the corresponding code:

Logcat: (edited)

E/getAvaArrStr: E/urlAva: E/getAvaArrStr: E/urlAva: E/getAvaArrStr: E/urlAva: E/getAvaArrStr: E/urlAva: E/getAvaArrStr: E/urlAva: /* Response */ E/ResponseAvatar: E/url: E/CheckArrBit: E/ResponseAvatar: E/url: E/CheckArrBit: E/ResponseAvatar: E/url: E/CheckArrBit: E/ResponseAvatar: E/url: E/CheckArrBit: 

MapsFragment.java: (Edited)

 RequestQueue queue = Volley.newRequestQueue(getActivity()); for (int i = 0; i < alAvaArr.size(); i++) { getAvaArrStr = alAvaArr.get(i); Log.e("getAvaArrStr", "" + getAvaArrStr); urlAva = BurblrUtils.BR_AVATAR_IMAGE + getAvaArrStr + "&android=1"; Log.e("urlAva", urlAva); requestAva = new StringRequest(Request.Method.GET, urlAva, new Response.Listener<String>() { @Override public void onResponse(String response) { if (response != null && !response.startsWith("<HTML>")) { Log.e("ResponseAvatar", response); dialog.dismiss(); try { Toast.makeText(getActivity(), "Running ", Toast.LENGTH_SHORT).show(); String url = response.replace("\\", ""); url = url.replace("\"", ""); Log.e("url", url); arrBitMap.add(url); Log.e("CheckArrBit", "" + arrBitMap); // Glide.with(getActivity()).load(url).placeholder(R.drawable.ic_launcher).error(R.drawable.ic_launcher).into(img); getSwipeImage(); myAppAdapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); dialog.dismiss(); } } else { dialog.dismiss(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error != null) { Log.e("error", error.toString()); dialog.dismiss(); } } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("file", getAvaArrStr); Log.e("paramsImg", "" + params); Log.e("RunningParams", "Testing"); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("Content-Type", "application/x-www-form-urlencoded"); return params; } }; queue.add(requestAva); queue.getCache().remove(urlAva); } 

Expected log response sequence:

 E/getAvaArrStr: -> E/urlAva: -> E/ResponseAvatar: -> E/url: -> E/CheckArrBit: 

I need to get an answer every time the loop starts. This means almost 8 times, based on the size of the array, I should get a response message, is this possible in a salvo? Any suggestion to solve this problem.

+5
source share
6 answers

You must create a function. The makeRequest function handles your next Api call

 public class MainActivity extends AppCompatActivity { RequestQueue queue; int mIndex = 0 ; ArrayList<String> alAvaArr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mQueue = Volley.newRequestQueue(getActivity()); alAvaArr = ///////// initialize here mIndex = 0; makeRequest(alAvaArr.get(mIndex)); } public void makeRequest( String arg){ getAvaArrStr = arg; Log.e("getAvaArrStr", "" + getAvaArrStr); urlAva = BurblrUtils.BR_AVATAR_IMAGE + getAvaArrStr + "&android=1"; Log.e("urlAva", urlAva); requestAva = new StringRequest(Request.Method.GET, urlAva, new Response.Listener<String>() { @Override public void onResponse(String response) { if (response != null && !response.startsWith("<HTML>")) { Log.e("ResponseAvatar", response); dialog.dismiss(); try { Toast.makeText(getActivity(), "Running ", Toast.LENGTH_SHORT).show(); String url = response.replace("\\", ""); url = url.replace("\"", ""); Log.e("url", url); arrBitMap.add(url); Log.e("CheckArrBit", "" + arrBitMap); // Glide.with(getActivity()).load(url).placeholder(R.drawable.ic_launcher).error(R.drawable.ic_launcher).into(img); getSwipeImage(); myAppAdapter.notifyDataSetChanged(); mIndex++; if(mIndex < alAvaArr.size()){ makeRequest(alAvaArr.get(mIndex)); } } catch (Exception e) { e.printStackTrace(); dialog.dismiss(); } } else { dialog.dismiss(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error != null) { Log.e("error", error.toString()); dialog.dismiss(); } } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("file", getAvaArrStr); Log.e("paramsImg", "" + params); Log.e("RunningParams", "Testing"); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("Content-Type", "application/x-www-form-urlencoded"); return params; } }; mQueue.add(requestAva); } 
+1
source

You create a RequestQueue inside a for ... loop

So there is no call queue ... Move it from the for loop

 RequestQueue queue = Volley.newRequestQueue(getActivity()); for(..){ ... queue.add(requestAva); } 
+2
source

Since Volley is asynchronous, therefore IMO, you should not put requests inside the for-loop, like code in your question. Please refer to the following code sample and then apply its logic to your application. Hope this helps!

 public class MainActivity extends AppCompatActivity { private int num = 0; private JsonArrayRequest jsonArrayRequest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final RequestQueue requestQueue = Volley.newRequestQueue(this); String url = "http://..."; jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.i("Num", String.valueOf(num)); Log.i("Response", response.toString()); if (num < 8) { num++; requestQueue.add(jsonArrayRequest); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Error", error.toString()); } }); num++; requestQueue.add(jsonArrayRequest); } } 

Logcat output as below:

 03-28 13:14:29.885 13262-13262/com.example.googlevolley I/Num: 1 03-28 13:14:29.885 13262-13262/com.example.googlevolley I/Response: [{"id":"1","name":"Information Technology"},{"id":"2","name":"Human Resources"},{"id":"3","name":"Marketing and PR"},{"id":"4","name":"Research and Developement"}] 03-28 13:14:29.935 13262-13262/com.example.googlevolley I/Num: 2 03-28 13:14:29.955 13262-13262/com.example.googlevolley I/Response: [{"id":"1","name":"Information Technology"},{"id":"2","name":"Human Resources"},{"id":"3","name":"Marketing and PR"},{"id":"4","name":"Research and Developement"}] 03-28 13:14:30.085 13262-13262/com.example.googlevolley I/Num: 3 03-28 13:14:30.085 13262-13262/com.example.googlevolley I/Response: [{"id":"1","name":"Information Technology"},{"id":"2","name":"Human Resources"},{"id":"3","name":"Marketing and PR"},{"id":"4","name":"Research and Developement"}] 03-28 13:14:30.245 13262-13262/com.example.googlevolley I/Num: 4 03-28 13:14:30.245 13262-13262/com.example.googlevolley I/Response: [{"id":"1","name":"Information Technology"},{"id":"2","name":"Human Resources"},{"id":"3","name":"Marketing and PR"},{"id":"4","name":"Research and Developement"}] 03-28 13:14:30.266 13262-13262/com.example.googlevolley I/Num: 5 03-28 13:14:30.266 13262-13262/com.example.googlevolley I/Response: [{"id":"1","name":"Information Technology"},{"id":"2","name":"Human Resources"},{"id":"3","name":"Marketing and PR"},{"id":"4","name":"Research and Developement"}] 03-28 13:14:30.296 13262-13262/com.example.googlevolley I/Num: 6 03-28 13:14:30.296 13262-13262/com.example.googlevolley I/Response: [{"id":"1","name":"Information Technology"},{"id":"2","name":"Human Resources"},{"id":"3","name":"Marketing and PR"},{"id":"4","name":"Research and Developement"}] 03-28 13:14:30.306 13262-13262/com.example.googlevolley I/Num: 7 03-28 13:14:30.306 13262-13262/com.example.googlevolley I/Response: [{"id":"1","name":"Information Technology"},{"id":"2","name":"Human Resources"},{"id":"3","name":"Marketing and PR"},{"id":"4","name":"Research and Developement"}] 03-28 13:14:30.316 13262-13262/com.example.googlevolley I/Num: 8 03-28 13:14:30.316 13262-13262/com.example.googlevolley I/Response: [{"id":"1","name":"Information Technology"},{"id":"2","name":"Human Resources"},{"id":"3","name":"Marketing and PR"},{"id":"4","name":"Research and Developement"}] 
+2
source

I will add another option caused by the words BNK

Because Volley is asynchronous ...

Here we have 2 types of solutions that essentially make synchronization of your requests.

1) a solution for synchronizing requests by starting them from the previous response callback (request chain)

2) my solution using Futures to synchronize calls, thus converting them to blocking calls (one is waiting for the previous one to complete).

both of them work and will run at almost the same speed.

however, they all work against the multithreaded benefits of Volley.

If your only goal is to link the URLs you provided first with the answers, then you can just have the MAPs and put them in the right place after receiving the response.

in this example I will use Map (urlAndResponses) to merge your 2 collections

alAvaArr and arrBitMap

so instead:

 for (int i = 0; i < alAvaArr.size(); i++) { getAvaArrStr = alAvaArr.get(i); 

You put:

  final Map<String, String> urlAndResponses = Collections.synchronizedMap(new HashMap<String, String>()); for (Map.Entry<String, String> entry:urlAndResponses.entrySet()) { final String getAvaArrStr = entry.getKey(); 

then in your callback instead:

 arrBitMap.add(url); 

You put:

 urlAndResponses.put(getAvaArrStr, url); 

This way you won’t have the logs as you want, but at any time you will get the answer in the right place and all requests will be executed asynchronously.

+1
source

To run volleyball requests several times (for example, in a for loop) with the log output strictly following the order you defined, you can do this -

1) put the code that you have in the "loop cycle" inside runnable

 Runnable runnable=new Runnable(){ //your code here }; 

2) Create a handler anywhere before the code above using

 Handler handler=new Handler(); 

and now put this line as the last line inside onResponse

 handler.post(runnable); 

3) Now your code will work in an infinite loop, so you need to create an exit condition. you can create a counter variable and increment it inside onResponse. Then just put handler.post () in an if condition, checking if the counter is <8 or something like that.

Using the handler, you can execute the volleyball request again without increasing the counter from onErrorResponse and you will not be able to process the request better than using the for loop.

Also, your exit condition may be some logical one that you will receive as an answer, and therefore you can let the server tell you how many requests to make instead of a fixed fixed number.

Thirdly (and, as I mentioned earlier) the code that you have in runnable, before you make a volleyball request, will always be executed after the previous request is completed, so you can use this strict order if you want.

If you have any doubts or some code does not work, a kind comment, so I can make the necessary changes.

0
source

From your requirements, I assume you need synchronous execution. So badly advise you to use futures. It is also important to note that in order not to block the main thread, you execute the entire cycle in a separate thread. eg:

 new Thread(new Runnable() { @Override public void run() { ..your loop... } }).start(); 

when creating a request:

 requestAva = new StringRequest(Request.Method.GET, urlAva, new Response.Listener<String>() { @Override public void onResponse(String response) { if (response != null && !response.startsWith("<HTML>")) { Log.e("ResponseAvatar", response); dialog.dismiss(); try { Toast.makeText(getActivity(), "Running ", Toast.LENGTH_SHORT).show(); String url = response.replace("\\", ""); url = url.replace("\"", ""); Log.e("url", url); arrBitMap.add(url); Log.e("CheckArrBit", "" + arrBitMap); // Glide.with(getActivity()).load(url).placeholder(R.drawable.ic_launcher).error(R.drawable.ic_launcher).into(img); getSwipeImage(); myAppAdapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); dialog.dismiss(); } } else { dialog.dismiss(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error != null) { Log.e("error", error.toString()); dialog.dismiss(); } } }) 

change to this:

 RequestFuture<String> future = RequestFuture.newFuture() { @Override public synchronized void onResponse(String response) { if (response != null && !response.startsWith("<HTML>")) { Log.e("ResponseAvatar", response); dialog.dismiss(); try { Toast.makeText(getActivity(), "Running ", Toast.LENGTH_SHORT).show(); String url = response.replace("\\", ""); url = url.replace("\"", ""); Log.e("url", url); arrBitMap.add(url); Log.e("CheckArrBit", "" + arrBitMap); // Glide.with(getActivity()).load(url).placeholder(R.drawable.ic_launcher).error(R.drawable.ic_launcher).into(img); getSwipeImage(); myAppAdapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); dialog.dismiss(); } } else { dialog.dismiss(); } super.onResponse(response); } @Override public synchronized void onErrorResponse(VolleyError error) { if (error != null) { Log.e("error", error.toString()); dialog.dismiss(); } super.onErrorResponse(error); } }; requestAva = new StringRequest(Request.Method.GET, urlAva, future, future) {... 

Notice that you are setting your future listeners, and your previous listeners are not realized in your future. then when you add the query

  queue.add(requestAva); 

change to:

 queue.add(requestAva); try { future.get(); // the response is handled by your Future synchroniously } catch (InterruptedException e) { // handle the error } catch (ExecutionException e) { // handle the error } 
0
source

Source: https://habr.com/ru/post/1245750/


All Articles