Android Tutorial StateManager - Helps managing Android applications settings and state

Discussion in 'Tutorials & Examples' started by Erel, Jun 19, 2011.

  1. Erel

    Erel Administrator Staff Member Licensed User

    StateManager is a code module which takes care of handling the application UI state and settings.

    Settings are the application configurable settings. These settings should be permanently kept.

    The methods for handling settings are pretty simple:
    StateManager.GetSetting (Key As String) As String: gets the value associated with the given key. An empty string will return if the key is not available. The settings will be loaded from a file if they were not loaded before.

    StateManager.GetSetting2 (Key As String, DefaultValue As String) As String: similar to GetSetting. The DefaultValue will return if the key was not found.

    StateManager.SetSetting(Key As String, Value As String): Associates the given value with the gives key. Note that there is no need to call SaveSettings after each call to SetSetting.

    StateManager.SaveSettings: saves the settings to a file. Usually you will want to call this method in Activity_Pause.

    UI State
    The UI state is a bit more interesting. In some cases Android may destroy our activity and then recreate it when needed. This happens for example when the user changes the screen orientation. If the user has entered some text in an EditText view then we want to keep this text. So instead of resetting the UI we are first saving the state and then we will restore it.

    Not all the elements are saved. Only elements which the user interacts with (like EditText text, Spinner chosen item, SeekBar value...).
    Using StateManager to handle the state is simple:
    Sub Activity_Create(FirstTime As Boolean)

    'Load the previous state
        If StateManager.RestoreState(Activity"Main"60) = False Then
    'set the default values
            EditText1.Text = "Default text"
            EditText2.Text = 
    "Default text"
    End If
    End Sub

    Sub Activity_Pause (UserClosed As Boolean)
    If UserClosed Then
    End If
    End Sub
    When the activity is paused we check if the user chose to close the activity (by pressing on the Back key). In that case we reset the state. The string parameter is the ActivityName value. StateManager can manage the state of multiple activities so the name is used to differentiate between the activities.
    If UserClosed=False then we want to save the state.
    The settings are saved in both cases.

    When the activity is created we call: StateManager.RestoreState. The last parameter is the validity period for this state. The state will not be loaded if more than the specified minutes have passed. Pass 0 for an unlimited period.
    RestoreState returns a boolean value. It returns true if the state was loaded. If the state wasn't loaded it is your responsibility to set the default value. This will be the case when the user runs the application for the first time.

    To use StateManager you should choose Project - Add Existing Module and add StateManager.bas which is included in the attached example. You should also add a reference to the RandomAccessFile library and Reflection library.


    Version 1.11 is attached. It adds support for saving and restoring TabHost views with their internal views.

    Attached Files:

    Last edited: Dec 21, 2015
    js1234, Ferbis, cxdzbl and 15 others like this.
  2. derez

    derez Expert Licensed User

    Leave some code for us to do by ourselves !

    If I have 5 edittext and the user has filled 3 of them - what will be displayed after pause & resume ?

    Edit: After reading the code I have the answer, but shouldn't "StateKeeper" be "StateManager" ?
    Last edited: Jun 19, 2011
    Peter Simpson likes this.
  3. Erel

    Erel Administrator Staff Member Licensed User

    The UI is kept as it was. The filled EditTexts will stay filled.

    Oops. It is now fixed.
  4. eps

    eps Well-Known Member Licensed User

    Erel, just to say thanks for this, it's exactly what I've been looking for :) Just integrating into my app and adjusting to suit! :)
  5. eps

    eps Well-Known Member Licensed User

    Okay... So I've got SaveState and RestoreState and mostly it works as expected.

    There is one oddity for me tho...

    I've altered the code, so that it stores items when Home or the Back button are used. This works fine when using the Home button, no problem, values are stored and restored.. but when using the Back Button it doesn't seem to want to store the value associated with a checkbox that I have.

    Any ideas?

    Other items, such as the Tabs and Panels are stored and then of course subsequently restored, but of course you can't restore something that wasn't stored, but why wouldn't it be stored?

    As mentioned, using the Home Button works perfectly! I capture the Back Button and call the Store service and so on, but it just doesn't seem to see that there is a checkbox.. Tabs are restored for instance, but the checkbox is just ignored...

    Last edited: Jul 7, 2011
  6. Erel

    Erel Administrator Staff Member Licensed User

    You should not catch the Back button. Just change Activity_Paused to:
    Sub Activity_Pause (UserClosed As Boolean)
    End Sub
    Watchkido1 likes this.
  7. eps

    eps Well-Known Member Licensed User

    Cheers Erel I will give it a go tonight..

    I capture the back button anyway, so thought I'd use that. Will the above be called after processing the back button?
  8. Erel

    Erel Administrator Staff Member Licensed User

    Yes. When the activity is closed due after the user presses on the back button then UserClosed=True. In my original code the state is not saved in this case. The idea is that if the user pressed on the back button then they do not intend to return to the current session.
  9. eps

    eps Well-Known Member Licensed User

    Yep, understood, it's just that I think my users will want the state saved, whatever way they exit the app. :)
  10. eps

    eps Well-Known Member Licensed User

    Nope, doesn't work, but I'm guessing it's my code...

    I've adjusted the example and it works a treat, Home button or Back button.

    FYI I have 4 tabs, so maybe I'm not storing the information from the right Activity, View or other??

  11. eps

    eps Well-Known Member Licensed User

    I think it's something to do with LoadLayout...
  12. eps

    eps Well-Known Member Licensed User

    Any ideas, anyone?

    If I use LoadLayout it scrambles the different views, rendering the app. a mess, I then get two checkboxes.. One which maintains it's value and then another which doesn't. What am I doing wrong here?

    Shall I post the code elsewhere?
  13. Erel

    Erel Administrator Staff Member Licensed User

    Please upload a small project that demonstrates the problem.
  14. awama

    awama Active Member Licensed User

    ScrollView state dosn't saved if screen-orientation turn

    Hi Erel,

    I test Statemanager and found that ScrollView state dosn't saved if screen-orientation turn. Scrollview show always green when I turn phone.

  15. Erel

    Erel Administrator Staff Member Licensed User

    I see it too. Seems to be related to a bug in Android animations. I've updated the file in the first post with a workaround.
  16. awama

    awama Active Member Licensed User

    Thanks Erel,

    now it works fine on my ZTE-Blade V2.1 and GalaxyS2 V2.3.3

  17. philfred

    philfred Member Licensed User

    StateManager saving lists with a bitmap

    Hi Erel,
    I have found this useful but i have been modifying the scrollviewlist demo by klaus as its very similar to what i need, i need to add a bitmap into the views, which now works but then it gets upset when statemanager tries to save the state.

    I am using this as I was struggling to work out the events and how there fired and how i was going to save things...

  18. rleiman

    rleiman Well-Known Member Licensed User

    Error compiling sample project

    Hi Erel,

    I tried to run the sample but it comes up with this error. It told me to clean the project and I still get the error when I do that:

    Compiling code. 0.02
    Generating R file. 0.00
    Compiling generated Java code. 5.35
    Convert byte code - optimized dex. 2.14
    Packaging files. 0.34
    Signing package file (debug key). Error

    jarsigner: attempt to rename bin\temp.ap_ to bin\temp.ap_.orig failed

    Cleaning your project may solve this problem. Tools - Clean Project
  19. Erel

    Erel Administrator Staff Member Licensed User

    Please open objects\bin and delete all files in this folder.
  20. jkurant

    jkurant Member Licensed User

    Can't compile StateManager

    I have added the StateManager code to my project but it won't compile. What do I need to do to make it recognize RandomAccessFile?

    Sub writeStateToFile
    Dim [COLOR="red"]raf[/COLOR] As [COLOR="Red"]RandomAccessFile[/COLOR]
    "red"]raf[/COLOR].Initialize(File.DirInternal, statesFileName, False)
    "red"]time[/COLOR] = DateTime.Now
    "red"]raf[/COLOR].WriteObject(states, True, [COLOR="red"]raf[/COLOR].CurrentPosition)
    End Sub
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice