I am having an issue with adding cookie on the cookie manager during startup.
Problem I am trying to solve is - to add the cookie in Sharedprefrence during login response and when application is killed or exited, retrieve that cookie and add to my cookie store so that Main activity will send the read command to server and server will see the cookie and know that user is already logged in.
Current Issue I am facing is - During login, I am able to save the cookie to shared prefrence. When application is killed and restarted I get the cookie string from shared prefrence but when I add that to my cookiemanager - it still takes me to login screen. Also, when I print the Sharedprefrence after that in my logs, I see URI as null, while in application - when I am setting the cookie - I see my URI matching the cookie get domain value (Not sure if it works exactly like this or not)
Flow is Mainactivity sends a read command to server, if server sees that there is no cookie and user is not logged in, it sends status 0; otherwise 1. If status is 0 then I move to login activity, otherwise to home screen activity. This works fine but only when application is killed, as cookie is deleted, It takes me to login screen.
Below is code:-
My Main activity/login activity and Home screen activity - Calls a class with Async task for httpconnection - which writes into shared preference.
Inside the doInbackground:-
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
List<HttpCookie> cookies = ((CookieManager)CookieHandler.getDefault()).getCookieStore().getCookies();
if (cookies.isEmpty()) {
Log.d("LOG_TAG","no cookies received");
} else {
for (int i = 0; i < cookies.size(); i++) {
Context context1 = application.getContext();
SharedPreferences sharedPreferences = context1.getSharedPreferences("Myprefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("cookie",cookies.get(i).toString());
editor.putString("URI",cookiedomain);
editor.commit();
}
}
Application class -
public class application extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
application.context = getApplicationContext();
SharedPreferences settings = getSharedPreferences("Myprefs", 0);
String silent = settings.getString("cookie", null);
String uri = settings.getString("URI",null);
if (silent != null) {
if (uri != null) {
HttpCookie httpcookie = new HttpCookie("user", silent);
URI myuri = URI.create(uri);
cookieManager.getCookieStore().add(myuri,httpcookie);
}
}
}
public static Context getContext() {
return application.context;
}
Will appreciate if someone can help me with it. I am really breaking my head here.