翻新中的缓存存在非静态和静态问题

时间:2019-02-10 12:01:31

标签: java android caching retrofit

我想在翻新中使用缓存,但是由于getCacheDir();

这是我的代码:

public class ServiceGenerator extends AppCompatActivity {

    public static final String API_BASE_URL = "https://myapiurl.com/";

    private static HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    private static Interceptor logging = interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);

    static File dir = getCacheDir();
    static Cache cache = new Cache(dir,10*1024*1024);
    private static OkHttpClient httpClient = new OkHttpClient.Builder()
            .cache(cache)
            .addInterceptor(logging)
            .build();

    private static Gson gson = new GsonBuilder()
            .setLenient()
            .create();
    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson));

    public static <S> S createService(Class<S> serviceClass) {
        Retrofit retrofit = builder.client(httpClient).build();
        return retrofit.create(serviceClass);
    }


}

错误为“无法从静态上下文中引用非静态方法'getCacheDir()'”

因此,我删除了所有静态变量,并收到关于createService()的另一个错误消息,即它不是非静态的。

如何解决此问题?

2 个答案:

答案 0 :(得分:0)

getCacheDir()不是static方法,因此不能由静态字段/方法调用。首先,您必须创建ServiceGenerator实例。我建议您将所有字段和方法设置为常规(非静态)并在ServiceGenerator onCreate回调中对其进行调用/分配。

public class ServiceGenerator extends AppCompatActivity {

    private static final String API_BASE_URL = "https://myapiurl.com/";

    private Retrofit retrofit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC);
        Cache cache = new Cache(getCacheDir(), 10 * 1024 * 1024);
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .cache(cache)
                .addInterceptor(loggingInterceptor)
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .client(httpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }

    protected <S> S createService(Class<S> serviceClass) {
        return retrofit.create(serviceClass);
    }
}

每个将扩展ServiceGenerator的活动都会创建一个服务。

答案 1 :(得分:0)

经过大量搜索,我发现答案在Context

 public static <S> S createService(Class<S> serviceClass,Context mContext) {
     File dir = new File(mContext.getCacheDir(),"http-cache");
     ...
 }