Search code examples
javaandroidfiletimerchronometer

How do I save chronometer elapsed time in android app


I'm developing a sort of parking meter counter app for a few specific locations. The app asks the user where he is (dropdown menu, saves column letter and number, like A6) and then shows a screen with the given location, a timer (chronometer class) counting up from 0 and the price that has to be paid on exit (calculated using elapsed hours * base price).

This all works nicely, until the user or the OS kills the app (task manager or memory management). Then, the next time the user opens the app, he's back at the main menu and his location, time and price has been lost.

I need a way to save all of the user's information and be able to load it up on app restart.

Initially I had thought to save the user's location and the exact time the chronometer started (DateTime.Now() maybe?) to a .txt file in the internal storage so that it would read:

 mallname,columnLetter,columnNumber,startTime

This way, if the app is killed, or any time the app is started up from scratch, the MainActivity will first check if a file.txt exists in the app's internal storage, if it does, it immediately starts the lastPage activity, reading the .txt file to pass the values as parameters (thus, the comma separation). If there's no such file, it would just carry on normally. The last page does contain a reset button that would delete the file so that the app can start up normally the next time it's used.

I don't know how efficient this method is, but it's the first thing that came to mind. However, I don't know how to go about this. I have this same exact method programmed in C# for Windows Phone, but I don't know how to translate it into Java for Android. Also, in C# I didn't actually use a chronometer, rather, I had the startTime saved and used a timer that would calculate startTime - DateTime.now() on every tick (every second) and update the textBlock to show this.

Any help would be greatly appreciated.


Solution

  • Usually user data should be saved to a SQLite database, however in your case, since you're talking about a few variables, it'd be much easier for you to save these values in the application's SharedPreferences.

    For every value you'd like to save, add this line to your Chronometer's onChronometerTick() method:

    PreferenceManager.getDefaultSharedPreferences(this).edit().putInt("your_key", <Your_value>).commit();
    

    This can later (whenever your application recovers from a crash, for example) be retrieved by:

    PreferenceManager.getDefaultSharedPreferences(this).getInt("your_key", <Default_value>);
    

    Regarding performance issues, if your Chronometer ticks once every second this should have no effect on your app's performances and is completely acceptable.