I would like to save some stuff on the SharedPreferences while being on a Interceptor. I can't find a way to do it because i can't find a way to access the context on the Interceptor (so not possible to use PreferencesManager, etc).
public class CookieInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
PreferenceManager.getDefaultSharedPreferences(Context ??)
}}
Any ideas ?
I'm using AndroidStudio & last version of OkHttp.
Thanks ;)
You can create a class that allows you to retrieve the context from anywhere (i.e. your interceptor):
public class MyApp extends Application {
private static MyApp instance;
public static MyApp getInstance() {
return instance;
}
public static Context getContext(){
return instance;
}
@Override
public void onCreate() {
instance = this;
super.onCreate();
}
}
Then add this to your manifest like this:
<application
android:name="com.example.app.MyApp"
And then in your interceptor, do this:
PreferenceManager.getDefaultSharedPreferences(MyApp.getContext());
You should not keep static instance of context, since it will lead to memory leak. Instead, you can change your architecture a bit to be able to send context as a parameter to the Interceptor.
// in your network operations class
// where you create OkHttp instance
// and add interceptor
public class NetworkOperations {
private Context context;
public NetworkOperations(Context context) {
this.context = context;
OkHttpClient client = new OkHttpClient.Builder()
// ... some code here
.addInterceptor(new CookieInterceptor(context))
// ... some code here
.build();
}
}
Then you can use that context instance in your Interceptor class.
public class CookieInterceptor implements Interceptor {
private Context context;
public CookieInterceptor(Context context) {
this.context = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
PreferenceManager.getDefaultSharedPreferences(context);
}
}
Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With