I want to use cache in retrofit, but I get an error because of getCacheDir();
This is my code:
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);
}
}
The error is "Non-static method 'getCacheDir()' cannot be referenced from a static context"
So I deleted all static variables and I get another error about createService()
that it couldn't be non-static.
How can I fix this problem?