How do I use new classes while being backwards compatible with android?
I need to use the CookieManager class for version 9 or later devices. My code looks like this;
public class HttpUtils {
private static CookieManager cookie_manager = null;
@TargetApi(9)
public static CookieManager getCookieManager() {
if (cookie_manager == null) {
cookie_manager = new CookieManager();
CookieHandler.setDefault(cookie_manager);
}
return cookie_manager;
}
}
When I run it on the 2.2 emulator; I have this error log;
Could not find class 'java.net.CookieManager', referenced from method com.application.utils.HttpUtils.getCookieManager
When I need CookieManager, I call this method by checking the OS version;
if (Build.VERSION.SDK_INT >= 9)
...
So; In my app, if the version is 2.2 or earlier; This method is never called. My question is why am I seeing this error log?
Solution
If I create an HttpUtils instance in the calling activity code outside of the SDK check, I can replicate it on the 2.2 emulator. For example:
HttpUtils utils = new HttpUtils();
if (Build.VERSION.SDK_INT >= 9)
{
Object test = utils.getCookieManager();
}
It doesn’t happen if I call a static method directly:
if (Build.VERSION.SDK_INT >= 9)
{
Object test = HttpUtils.getCookieManager();
}
If you have
something else non-static in your HttpUtils class, you have to move the CookieManager section to a different helper class and just call it statically… Or instantiate HtppUtils:: after your SDK checks
if (Build.VERSION.SDK_INT >= 9)
{
HttpUtils utils = new HttpUtils();
Object test = utils.getCookieManager();
}