java - Is it good to keep static references to Locale instances? -
so trying make app in can change language (in preference activity) system default or specific language. whenever change language app restarted , new locale selected. when first activity starts, saves locale has used static variable in utils class. in every activity oncreate method load locale.
now, clarification, here's locale part of utils class:
private static locale locale = null; public static boolean islocalenull() { return locale == null; } public static void setlocale(locale locale) { utils.locale = locale; } public static void loadlocale(context basecontext) { if (locale == null) return; locale.setdefault(locale); configuration config = new configuration(); config.locale = locale; basecontext.getresources().updateconfiguration(config, basecontext.getresources().getdisplaymetrics()); }
here's oncreate on first activity (only locale part):
if (!utils.islocalenull()) { string locale = preferencemanager.getdefaultsharedpreferences(getbasecontext()) .getstring(getresources().getstring(r.string.prefskeylanguage), "default"); if (locale != null && !locale.equals("default")) utils.setlocale(new locale(locale)); }
and here's how load locale in activities:
utils.loadlocale(getbasecontext());
finally, in loadlocale have if (locale == null) return;
, in locale loader have if (... && !locale.equals("default"))
means locale null if system default selected means locale won't change if system default selected.
everything's perfect! mean, works expected. can fail in cases? idea? know holding static references instances bad idea in cases. 1 of cases? if yes, should do?
thanks!
you right, not idea because android rid of static variable need memory (and happens quite often).
you should set , retrieve locale
using sharedpreferences.
to deal object
s in sharedpreferences use gson
:
to save
editor prefseditor = mprefs.edit(); gson gson = new gson(); string json = gson.tojson(myobject); prefseditor.putstring("myobject", json); prefseditor.commit();
to retreive
gson gson = new gson(); string json = mprefs.getstring("myobject", ""); myobject obj = gson.fromjson(json, myobject.class);
Comments
Post a Comment