So my app needed a cookie store that persists over the app closing, device reboot etc. I decided to use the sharedPreferences for this. The class works pretty well, in both my tests and on the device. However there are couple of things I think can be improved. First is error handling. The problem is I cannot throw the errors further up in the app as the cookiestore interface doesn't not allow it. Secondly I have made a persistantcookie so I have a concrete class to serialise. I then convert that to the cookie interface. It seems an ugly way to do it. So any pointers would be very much appreciated.
public class BetterPersistantCookieStore implements CookieStore {
private static final String TAG = BetterPersistantCookieStore.class.getSimpleName();
private SharedPreferences sharedPreferences;
private ObjectMapper objectMapper = new ObjectMapper();//TODO pass serializer and deserialiser into constructor
private static final String COOKIES_KEY = "cookiesKey";
@Inject
public BetterPersistantCookieStore(SharedPreferences sharedPreferences) {
this.sharedPreferences = sharedPreferences;
}
@Override
public void addCookie(Cookie cookie) {
List<PersistantCookie> cookieList = getPersistantCookies();
int len = cookieList.size();
for (int i = 0; i < len; ++i) {
Cookie tempCookie = cookieList.get(i);
if (cookie.getName().equals(tempCookie.getName())) {
cookieList.remove(i);
}
}
cookieList.add(new PersistantCookie(cookie));
sharedPreferences.edit().putString(COOKIES_KEY, listToString(cookieList)).commit();
}
@Override
public List<Cookie> getCookies() {
return convertPersistantCookiesToCookies(getPersistantCookies());
}
@Override
public boolean clearExpired(Date date) {
List<PersistantCookie> cookieList = getPersistantCookies();
int len = cookieList.size();
boolean returnValue = false;
for (int i = 0; i < len; ++i) {
Cookie cookie = cookieList.get(i);
if (cookie.isExpired(date)) {
cookieList.remove(i);
returnValue = true;
}
}
sharedPreferences.edit().putString(COOKIES_KEY, listToString(cookieList)).commit();
return returnValue;
}
@Override
public void clear() {
sharedPreferences.edit().remove(COOKIES_KEY).commit();
}
private List<PersistantCookie> getPersistantCookies() {
return stringToList(sharedPreferences.getString(COOKIES_KEY, ""));
}
private List<PersistantCookie> stringToList(String value) {
try {
return objectMapper.readValue(value, TypeFactory.collectionType(ArrayList.class, PersistantCookie.class));
} catch (IOException e) {
e.printStackTrace();
return new ArrayList<PersistantCookie>(0);
}
}
private String listToString(List<PersistantCookie> cookies) {
try {
return objectMapper.writeValueAsString(cookies);
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
private List<Cookie> convertPersistantCookiesToCookies(List<PersistantCookie> persistantCookies) {
List<Cookie> cookies = new ArrayList<Cookie>();
for (Cookie cookie : persistantCookies) {
cookies.add(cookie);
}
return cookies;
}
}