Android Tutorial StateManager - Helps managing Android applications settings and state

Status
Not open for further replies.
Edit: StateManager was written in 2011. I don't recommend using it for new projects. Use B4XPages + KVS2 instead.

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

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:
B4X:
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
        StateManager.ResetState("Main")
    Else
        StateManager.SaveState(Activity, "Main")
    End If
    StateManager.SaveSettings
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.

statemanager_1.png


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

Attachments

  • StateManager.zip
    11.7 KB · Views: 1,869
Last edited:

derez

Expert
Licensed User
Longtime User
Erel
Leave some code for us to do by ourselves !

Question:
If the user has entered some text in an EditText view
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:

eps

Expert
Licensed User
Longtime 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! :)
 

eps

Expert
Licensed User
Longtime 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...

hmmm...
 
Last edited:

eps

Expert
Licensed User
Longtime 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?
 

eps

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

eps

Expert
Licensed User
Longtime 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??

:(
 

eps

Expert
Licensed User
Longtime 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?
 

awama

Active Member
Licensed User
Longtime 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.

Walter
 

awama

Active Member
Licensed User
Longtime User
Thanks Erel,

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

Walter
 

philfred

Member
Licensed User
Longtime 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...

Regards
Phil
 

rleiman

Well-Known Member
Licensed User
Longtime 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
 

jkurant

Member
Licensed User
Longtime 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?

B4X:
Sub writeStateToFile
   Dim [COLOR="red"]raf[/COLOR] As [COLOR="Red"]RandomAccessFile[/COLOR]
   [COLOR="red"]raf[/COLOR].Initialize(File.DirInternal, statesFileName, False)
   [COLOR="red"]time[/COLOR] = DateTime.Now
   [COLOR="red"]raf[/COLOR].WriteObject(states, True, [COLOR="red"]raf[/COLOR].CurrentPosition)
   [COLOR="red"]raf[/COLOR].Close
End Sub
 
Status
Not open for further replies.
Top