处理OnErrorResponse方法-排球

时间:2018-06-30 19:57:03

标签: java android nullpointerexception android-volley

我正在使用齐射从json格式的服务器中获取数据。连接到Wifi时一切正常。但是,当用户连接到移动数据时,尤其是在移动数据连接速度较慢时,将调用OnErrorResponse方法。我已将Toast消息放入OnErrorResponse方法中。在某些设备中,此Toast消息因NullPointerException而崩溃,而在其他设备中,它运行正常。

如果我等待了很长时间,但结果仍未显示,则应用程序崩溃并出现内存不足错误。请帮助我。

如何有效处理这些问题?

代码:

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)

1 个答案:

答案 0 :(得分:1)

您可以定义重试次数以使成功执行为

jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
    1000*5, 
    /*DefaultRetryPolicy.DEFAULT_MAX_RETRIES*/ 3, 
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
songQueue.add(jsonObjectRequest);

关于NPE。 It is possible that VolleyError is null,以便您可以使用

if(error!=null && error.getMessage()==null)