繁体   English   中英

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.gson.JsonElement.toString()' on a null object reference

[英]java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.gson.JsonElement.toString()' on a null object reference

  private void getNewPhotos() {
        Call<JsonElement> call1 = RestClient.post().getNewPhotos(Config.NEW_ID, Config.unsplash_access_key);
        call1.enqueue(new Callback<JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
                //  progressDialog.dismiss();
                newPhotoslist.clear();
                Log.e("FeatureNews", response.body().toString());
                if (response.isSuccessful()) {

                    JSONArray jsonArr = null;


                    try {
                        jsonArr = new JSONArray(response.body().toString());
                        if (jsonArr.length() > 0) {
                            for (int i = 0; i < jsonArr.length(); i++) {
                                JSONObject json2 = jsonArr.getJSONObject(i);
                                String id=json2.getString("id");

                                JSONObject object=json2.getJSONObject("urls");
                                String url=object.getString("regular");

                                JSONObject objectUser=json2.getJSONObject("user");
                                JSONObject objectUserProfile=objectUser.getJSONObject("profile_image");
                                String userprofile=objectUserProfile.getString("large");


                                newPhotoslist.add(new PhotosBean(id,url,userprofile));

                            }

                            bindTrendData();

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            }

您应该在检查成功后移动日志。 一般来说,除非您有充分的理由假设变量不是 null,否则最好检查一下。 顺便说一句,您不需要显式调用toString ,您可以执行类似""+response.body()的操作,最终您将获得null

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM