Вопрос

I have a small DB and read the required extract of data in a Singleton object stored statically like this in a class called MainDataManager:

public class MainDataManager {
    private static Context context;
    public static MainDataManager mainDataManager = null;

    public static MainDataManager getInstance(Context ctx) {
        context = ctx;
        if (mainDataManager == null) {  
           ...get the data from DB
          ...put the data in static mainDataManager variable 
          } 
        return mainDataManager;
        }

Now in every class/activity of the app I can access the MainDataManager.mainDataManager data easily.

At some time I would like to save the data back to the database.

Currently I do this on each activity in

 @Override
    protected void onPause() {
    super.onPause();
    saveState(); //saves the mainDataManager's data to the DB
    }

I would like to avoid this and think it is actually "save" enough if I update the database only when the user exits the app (whatever this means) - or even better when Android wants to destroy the MainDataManager object.

While I could put my saveState() call in activities in the onDestroy() method - I would prefer to only save the data to DB if the MainDataManager object gets destroyed. But there is no onDestroy() for a normal object.

What would be the best way to handle that?

ps the reason why I do not want to saveState() in each activity's onDestroy() is, because saving to database is quite slow even with very little data (esp. on older Android phones!) and this is just not the logic - just because any activity is beeing destroyed- to then update the DB.

Many thanks

Это было полезно?

Решение

What would be the best way to handle that?

The way you are presently handling it, albeit perhaps using an AsyncTask from onPause(), and only from activities where you are changing the data, and perhaps using some sort of isDirty flag to let you know if data does need to be persisted.

The real reason you do not want to wait until onDestroy() is that onDestroy() is not guaranteed to be called.

I would prefer to only save the data to DB if the MainDataManager object gets destroyed.

That object will never be "destroyed" -- it will live until the process is terminated.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top