Lorsque mon application passe en arrière-plan, mes objets (statique et singleton) sont effacés. J'ai donc essayé de stocker ces objets dans Applicaton Context. J'utilise le code suivant. Accounts.create (getApplicationContext()) sera appelé une fois pour stocker l'instance de comptes. Est-ce possible (fiable) pour stocker des objets dans le contexte d'application?Stocker des objets dans ApplicationContext
Est-ce possible (fiable) pour stocker des objets dans le contexte d'application? Je ne suis pas sûr que la manière suivante soit correcte ou non. s'il vous plaît guider ..
public class Init extends Application {
private Hashtable<Object, Object> globalStore = new Hashtable<Object, Object>();
public void putToGlobalStore(Object key, Object value) {
globalStore.put(key, value);
}
public Object takeFromGlobalStore(Object key) {
return this.globalStore.get(key);
}
public void removeFromGlobalStore(Object key) {
this.globalStore.remove(key);
}
public boolean containsInGlobalStore(Object key) {
return this.globalStore.containsKey(key);
}
}
public class Accounts {
protected Accounts(String name, Context context) {
Init init = (Init) applicationContext;
init.putToGlobalStore(name, this);
}
private static Init applicationContext;
public static void create(Context context) {
if (context instanceof Application)
applicationContext = (Init) context;
else
applicationContext = (Init) context.getApplicationContext();
if (applicationContext.containsInGlobalStore(GLOBAL_NAME))
Logger.log("Warning " + GLOBAL_NAME
+ " is already created. This will remove all old datas");
new Accounts(GLOBAL_NAME, applicationContext);
}
private static final String GLOBAL_NAME = "accounts";
public static Accounts getInstance() {
try {
return (Accounts) applicationContext
.takeFromGlobalStore(GLOBAL_NAME);
} catch (Exception e) {
Logger.log("GLOBAL_NAME Lost");
return null;
}
}
S'il vous plaît aider.
Merci pour la réponse. Ce dont j'ai besoin est de stocker des données à travers l'application quand elle est en cours d'exécution –