android - 使用Retrofit OKhttp RxJava 无法完成离线缓存 出现空指针问题

查看:381
本文介绍了android - 使用Retrofit OKhttp RxJava 无法完成离线缓存 出现空指针问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

去除以下代码 程序正常运行 将不会出现空指针任务 但是无法完成离线缓存

  File cacheFile = new File(AppContext.getContext().getCacheDir(), "newsList");//设置缓存路径
        int cacheSize = 10 * 1024 * 1024; // 10 MiB 设置缓存大小
        Cache cache = new Cache(cacheFile, cacheSize);

  
                .addInterceptor(netInterceptor)
                .addNetworkInterceptor(netInterceptor)
                .cache(cache)

出错Log

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                 Process: com.example.axtonsun.zhihudaily, PID: 18394
                                                                                 java.lang.NullPointerException
                                                                                     at com.example.axtonsun.zhihudaily.Net.RetrofitManager.<init>(RetrofitManager.java:39)
                                                                                     at com.example.axtonsun.zhihudaily.Net.RetrofitManager.builder(RetrofitManager.java:35)
                                                                                     at com.example.axtonsun.zhihudaily.View.Fragment.RvList.loadLatestNews(RvList.java:90)
                                                                                     at com.example.axtonsun.zhihudaily.View.Fragment.RvList.initData(RvList.java:84)
                                                                                     at com.example.axtonsun.zhihudaily.View.Fragment.BaseFragment.onActivityCreated(BaseFragment.java:25)
                                                                                     at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:2201)
                                                                                     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1326)
                                                                                     at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                                                                                     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                                                                                     at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
                                                                                     at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)

完整代码

public class RetrofitManager {

    private ZhiHuService mService;
    private OkHttpClient mBuilder;
    private Retrofit retrofit;

    public static RetrofitManager builder(){
        return new RetrofitManager();
    }

    private RetrofitManager() {
        File cacheFile = new File(AppContext.getContextObject().getCacheDir(), "newsList");//设置缓存路径
        int cacheSize = 10 * 1024 * 1024; // 10 MiB 设置缓存大小
        Cache cache = new Cache(cacheFile, cacheSize);

        mBuilder = new OkHttpClient.Builder()
                .addInterceptor(netInterceptor)
                .addNetworkInterceptor(netInterceptor)
                .cache(cache)
                .build();

        retrofit = new Retrofit.Builder()
                .client(mBuilder)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(API.BASE_ZHIHU_URL)
                .build();
        mService = retrofit.create(ZhiHuService.class);
    }


    //拦截器
    private static Interceptor netInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if(!Utility.checkNetworkConnection(AppContext.getContextObject())){
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }
            Response originalResponse = chain.proceed(request);
            if(Utility.checkNetworkConnection(AppContext.getContextObject())){
                //有网的时候读接口上的@Headers里的配置
                String cacheControl = request.cacheControl().toString();
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, max-age=" + cacheControl)
                        .removeHeader("Pragma")
                        .build();
            }else{
                int maxTime = 60 * 60 * 24 * 7;//缓存过期时间为七天
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale="+maxTime)
                        .removeHeader("Pragma")
                        .build();
            }
        }
    };


    public Observable<Latest> getLatest(){
        return mService.getLatest();
    }

    public Observable<Hot> getHot(){
        return mService.getHot();
    }
    public Observable<DetailStories> getDetail(int id){
        return mService.getDetail(id);
    }

}

AppContext代码

public class AppContext extends Application {
    public static Context context;
    private SharedPreferencesUtils utils;
    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        utils = new SharedPreferencesUtils(context);
        boolean isNightMode = utils.isNight();
        if (isNightMode) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        }
    }
    public static Context getContext() {
        return context ;
    }
}

我发现是因为newsList==null 才出现的空指针 所以 我应该怎么修改呢
还有一种错误 我发现AppContext.getContext() 得到的context 为空 所以 到底是 哪里出错了

我将AppContext.getContext().getCacheDir() 改为路径 不报错了 但是 打开App 加载不出来数据

File cacheFile = new File(AppContext.getContext().getCacheDir(), "newsList");

解决方案

清单文件manifest 里面没有设置你的自定义application是启动的application吧

这篇关于android - 使用Retrofit OKhttp RxJava 无法完成离线缓存 出现空指针问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆