代码之家  ›  专栏  ›  技术社区  ›  Романыч

如果缓存为空,则对NPE进行改装

  •  0
  • Романыч  · 技术社区  · 7 年前

    我添加了缓存的可能性,并且会发生以下脚本: 如果以前上传过页面,一切正常,但是如果我第一次没有互联网 然后应用程序崩溃并引发错误

    NullPointerException: Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference
        at java.util.ArrayList.<init>(ArrayList.java:171)
        at n.MainDetailTrainFragment$3.onResponse(MainDetailTrainFragment.java:171)
    

    我理解这个错误,但我如何修复它?

    不要严格判断,我只是在学习。 这是我的密码^

    progressBarTrain.setVisibility(View.VISIBLE);
        Log.d(TAG, "getProducts");
    
       final OkHttpClient client = new OkHttpClient
               .Builder()
               .cache(new Cache(getActivity().getCacheDir(), 10 * 1024 * 1024)) // 10 MB
               .addInterceptor(new Interceptor() {
                   @Override public okhttp3.Response intercept(@NonNull Chain chain) throws IOException {
                       Request request = chain.request();
                       if (NetworkUtils.isNetworkAvailable(getActivity())) {
                           request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
                       } else {
                           request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
                       }
                       return chain.proceed(request);
                   }
               })
               .build();
    
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MY_URL)
                .client(client)
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .build();
    
        retrofit.create(myTrainInterface.class)
                .getProducts(APP_ID, FROM_CITY, position_0, "everyday")
                .enqueue(new Callback<Responce>() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onResponse(@NonNull Call<Responce> call, @NonNull Response<Responce> response) {
                        progressBarTrain.setVisibility(View.INVISIBLE);
                        if (response.body() != null) {
                            kk = response.body().products;
                        }
                        ArrayList<Responce.Item> p = new ArrayList<>(kk);
                        String s = String.valueOf(response.body());
    
    
    
    
                        adapter = new DetailTrainAdapter(p);
                        recyclerView.setAdapter(adapter);
                        Log.d(TAG, s);
    
                        textError.setVisibility(TextView.INVISIBLE);
                        textErrorRestart.setVisibility(TextView.INVISIBLE);
                    }
    
                    @Override
                    public void onFailure(@NonNull Call<Responce> call, @NonNull Throwable throwable) {
                        Log.d(TAG, "onFailure" + throwable.getLocalizedMessage());
                        textError();
                    }
                });
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   user2340612    7 年前

    当变量 kk null . 查看您的代码,您将从响应中创建一个列表(如果不是 无效的 )然后用它填充您的用户界面。但是,如果响应是 无效的 你没有做任何分配给 KK ,因此它保持其以前的值(很可能 无效的 ,考虑到NPE)。

    避免这种情况的一个可能的解决方案是执行 所有的逻辑 只有当 response.body() != null ,否则可能需要执行其他操作(例如,显示错误)。