Handle OnErrorResponse Method - Volley
Handle OnErrorResponse Method - Volley
I'm fetching data from a server in json format using volley. Everything works fine when connected to Wifi. But when user is connected to mobile data and especially if mobile data connection is slow OnErrorResponse method is called. I have put a Toast message in OnErrorResponse method. In some devices this toast message crashes with NullPointerException while in others it runs fine.
Also if I wait for a long time, and the results are not yet displayed then app crashes with outofmemory error. Please help me.
How to handle these problems efficiently?
Code:
private RequestQueue songQueue = songQueue = Volley.newRequestQueue(getContext());
private void getNewSongs() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, newSongsUrl, null, new Response.Listener<JSONObject>() {
@SuppressLint("LongLogTag")
@Override
public void onResponse(JSONObject response) {
JSONObject artistObject = null;
String artist = "";
String albumID = "";
String artistID = null;
try {
JSONObject songListObjects = response.getJSONObject("new_song");
if(songListObjects.has("data")){
JSONObject data = songListObjects.getJSONObject("data");
if(data.has("song_list")) {
JSONArray songList = data.getJSONArray("song_list");
for (int i=0;i<5;i++){
JSONObject songListObject = songList.getJSONObject(i);
if (songListObject.has("mid")) {
Log.e("SongListObject has", "songmid");
String songID = songListObject.getString("mid");
String songTitle = songListObject.getString("name");
long duration = songListObject.getLong("interval") * 1000;
Log.e("Title:", songTitle);
Log.e("Duration:", String.valueOf(duration));
JSONObject albumObject = songListObject.getJSONObject("album");
if(albumObject.has("mid")){
albumID = albumObject.getString("mid");
}
JSONArray artistArray = songListObject.getJSONArray("singer");
for (int j = 0; j < artistArray.length(); j++) {
artistObject = artistArray.getJSONObject(j);
if (j == 0) {
if (artistObject.has("name")) {
Log.e("ArtistObject: ", "has name");
artist = artistObject.getString("name");
artistID = artistObject.getString("mid");
}
} else {
if (artistObject.has("name")) {
Log.e("ArtistObject: ", "has name");
artist = artist + " ft. " + artistObject.getString("name");
}
}
}
SongInfoModel songInfoModel = new SongInfoModel(123, songTitle,artistID, ((artist == null || (artist.length() == 0)) ? "Unknown" : artist), duration, songData, albumArtURL);
SoundCloudNewSongs.add(songInfoModel);
if (getView() != null){
getView().findViewById(R.id.onlineProgressLoad).setVisibility(View.GONE);
getView().findViewById(R.id.mainLayout).setVisibility(View.VISIBLE);
}
}
}
}
}
newSongsAdapter = new NewSongsAdapter(SoundCloudNewSongs, getContext(),listenerOnline,1);
recyclerView_newSongs.setAdapter(newSongsAdapter);
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
@SuppressLint("LongLogTag")
@Override
public void onErrorResponse(VolleyError error) {
if(error.getMessage()==null)
Toast.makeText(getActivity(), "Timeout error :(", Toast.LENGTH_SHORT).show();
else Toast.makeText(getActivity(), "Timeout error :(", Toast.LENGTH_SHORT).show();
}
});
songQueue.add(jsonObjectRequest);
}
Logcat:
java.lang.NullPointerException:
at android.widget.Toast.<init> (Toast.java:114)
at android.widget.Toast.makeText (Toast.java:277)
at android.widget.Toast.makeText (Toast.java:267)
at com.musicplayer.musicana.OnlinePlaySupport$9.onErrorResponse (Unknown Source:15)
at com.android.volley.Request.deliverError (Unknown Source:8)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run (Unknown Source:62)
at android.os.Handler.handleCallback (Handler.java:790)
at android.os.Handler.dispatchMessage (Handler.java:99)
at android.os.Looper.loop (Looper.java:164)
at android.app.ActivityThread.main (ActivityThread.java:6518)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:807)
setRetryPolicy
If you are recommending this solution for second problem, it is okay. But for the first one?
– Sebin Paul
Jun 30 at 20:05
yes, the solution is for first one, you define the time and number of retries , let me show you
– Pavneet_Singh
Jun 30 at 20:05
If the volley request fails the first time then ofcourse the onErrorResponse method will invoked, hence the crash. Right?
– Sebin Paul
Jun 30 at 20:07
My app is published actually. I'll post the google console crash report.
– Sebin Paul
Jun 30 at 20:25
1 Answer
1
You can define the number of retries to get the successful execution as
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
1000*5,
/*DefaultRetryPolicy.DEFAULT_MAX_RETRIES*/ 3,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
songQueue.add(jsonObjectRequest);
About NPE. It is possible that VolleyError is null so you can use
if(error!=null && error.getMessage()==null)
60*1000*5 is for?
– Sebin Paul
Jun 30 at 20:11
And again, if the request fails, the OnErrorResponse method is called, right?
– Sebin Paul
Jun 30 at 20:12
bit modification
1000*5 mean five second delay , where 1000 is milliseconds and the purpose of retries is to make the request successful with max number of tries– Pavneet_Singh
Jun 30 at 20:19
1000*5
Ok, so if I got this right it means that request will be send 3 times(each of 5 seconds timeout) until success, right?
– Sebin Paul
Jun 30 at 20:21
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
you can set number of retries using
setRetryPolicy, but out of memory error is a different issue, post the stack trace– Pavneet_Singh
Jun 30 at 20:02