Search code examples
androidandroid-asynctaskactivity-lifecycle

saving data safely before Activity is destroyed


i need to save some crucial importance data when user closes my app. i prefere to do this in Activity's onPause(), as it is the latest method guaranteed to be called before the application is destroyed no matter what is the reason of its destruction. however, i save the data in a database, so i use an AsyncTask. from my AsyncTask, when it's finished, i call a callback method on my Activity reference i have saved in the AsyncTask before, where i put some variables to SharedPreferences indicating that the data has been successfully put to database.

my question is: is the AsyncTask guaranteed to finish and the callback to be called on an alive Activity reference before it gets destroyed? If not, how to ensure that data is written to database before Activity is destroyed?


Solution

  • You don't need to implement a CallBack method to save in your SharedPreferences that you have updated the Database.

    You can simply, if you really need a database for your info, create a flag in your SharedPreferences called isDataExistToLoad

    This flag has to be initially False, and within the Thread that will store your info into the Database set it to True.

    public void updateUserStatus(ArrayList<Object> data){
        try{
             DBController.save(data);
             SharedPReferencesController.setDataExistToLoad(true);
        }catch(Exception e){
             e.printStackTrace();
             SharedPReferencesController.setDataExistToLoad(false);
        }
    }
    

    Whenever you open your app, check on this flag. If it is True go load from database then set it to False. If it is False leave it as it is because the previous transaction was not successfully done.

    My question is: is the AsyncTask guaranteed to finish and the callback to be called on an alive Activity reference before it gets destroyed? If not, how to ensure that data is written to database before Activity is destroyed?

    My Answer is: Part of the AsyncTask runs in a separate Thread which is DoInBackground and you cannot ensure that the Activity will still be survived until it is done. If you tried to perform any other task in postExcute() which runs on UITread after finishing the background thread work. Your app might crash. That's why I don't recommend that.