Updating An Object Stored In One Activity From Another Activity
Solution 1:
save your array list in shared preference like this create a AppPreference Class:-
publicclassAppPreference {
privatestaticSharedPreferences mPrefs;
privatestaticSharedPreferences.Editor mPrefsEditor;
publicstaticSet<AppEngine> getList(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getStringSet("AppEngineList", null);
}
publicstaticvoidsetList(Context ctx, ArrayList<AppEngine> value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
Set<String> set = newHashSet<>();
set.addAll(value);
mPrefsEditor.putStringSet("AppEngineList", set);
mPrefsEditor.commit();
}
}
set your value from first activity like this:-
setList(YourActivity.class, list);
and get your list from anywhere in you app:-
ArrayLis<AppEngine> list = AppPreference.getList(yourActivity.class);
Solution 2:
If you only want the appEnginge object to persist during a single app session and not persist trough a complete app close/restart, then you should use a handler class.
EngineHandler.java:
publicstaticclassengineHandler {
publicstatic appEnginge _appEngine;
}
and then just call
engineHandler._appEngine = _myAppengine;
engineHandler._appEngine.getList().add(new Event);
from your activity(s). The engineHandler will be accessible from any activity in your application.
Solution 3:
You can use Singleton design Pattern.
You create one object from AppEnginRepository with eventList field and in your app you just get it and each time you want, you change it.
publicclassAppEnginRepository {
private List<Event> eventList;
privatestatic final AppEnginRepository ourInstance = new AppEnginRepository();
publicstatic AppEnginRepository getInstance() {
return ourInstance;
}
privateAppEnginRepository() {
eventList = new ArrayList<>();
}
public List<Event> getEventList() {
return eventList;
}
publicvoidsetEventList(List<Event> eventList) {
this.eventList = eventList;
}
}
In your Activities
AppEnginRepository enginRepository=AppEnginRepository.getInstance();
List<Event> eventList=enginRepository.getEventList();
eventList.add(new Event());
int eventListSize=eventList.size();
Solution 4:
It would be good to think each Activity is totally separated execution. Technically it's arguable, but it is good assumption to design cleaner and safer software.
Given assumption, there are several approaches to maintain data across Activities in an app.
- As @Sandeep Malik's answer, use SharedPreference OS-given storage.
- Similar to @Joachim Haglund's answer, use Singleton pattern to maintain an object in app.
- Or, use small database like Realm.
Every approach has similar fashion; there should be an isolated and independent storage which is not belonged to one of Activity but belonged to ApplicationContext or underlying framework.
Post a Comment for "Updating An Object Stored In One Activity From Another Activity"