I have an android app which uses several singleton objects. These objects are used in many activities. When an exception is thrown in an activity different fields in my singletons become null and all other activities also throw exceptions. For example I have a singleton class to handle my cookie which has a static HTTPCookie
field , and if in any activity an exception occurs this cookie field becomes null
too.
I would like to know why is this happening. How can I prevent this from happening?
UPDATE: code for one of my singletons.
public class CookieHandler {
public interface CookieHandlerCallback {
void OnNewCookieReceived();
void OnNewCookieFailed();
}
public static HttpCookie myCookie;
private static CookieHandler singleton = new CookieHandler();
private static CookieHandlerCallback cookieHandler;
private static Context context;
public static CookieHandler getInstance() {
return singleton;
}
private CookieHandler() {
}
public HttpCookie getMyCookie() {
return myCookie;
}
public static void setupInterface(CookieHandlerCallback co) {
cookieHandler = co;
}
public static void getNewCookie() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = prefs.getString("cookie", "");
myCookie = gson.fromJson(json, HttpCookie.class);
AppidoRetroAPI apiRetro = RetrofitService.getAppidoAPI();
Call<ResponseBody> call = apiRetro.getCookie(myCookie == null ? "" : myCookie.getValue());
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.code() == 401) {
Log.d("app process", "my debug" + "requestCategories in code 401 ");
String headerCookie = response.headers().get(ApiCnst.COOKIES_HEADER);
if (headerCookie != null) {
myCookie = new HttpCookie(ApiCnst.MY_COOKIE_NAME, headerCookie);
Gson gson = new Gson();
String json = gson.toJson(myCookie);
myCookie = gson.fromJson(json, HttpCookie.class);
editor.putString("cookie", json);
editor.commit();
}
} else if (response.code() == 200) {
UserProfileInfo.getInstance().setIs_logged_in(true);
try {
JSONObject jsonObject = new JSONObject(HttpManager.JsonTOString(response.body().byteStream()));
UserProfileInfo.getInstance().setUserJson(jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
Log.d("app process", "my debug" + "requestCategories in code 200 ");
}
cookieHandler.OnNewCookieReceived();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
cookieHandler.OnNewCookieFailed();
}
});
}
public static void updateContext(Context ctx) {
context = ctx;
}