Save Current State On Mobile Device

By default, when you exit  and then re-enter a LiveCode created mobile app no state is saved and your application does not resume from where it left off.

This lesson will explain how to create a simple app, save the state of an app to a text file when the app closes and when re-opened, have this state re-applied.

Create a Stack with Two Cards

Create a Stack with Two Cards

Create a new stack with two cards. Card one named "one" and Card two names "two". I have set the size of this stack to 320 x 480

Create some navigation buttons so you can go to and from each card (go next card, go previous card)

Now, create some graphics on each card so that when you navigate, you can tell you are on a new card

Create a file that saves the state on shutdown

Create a file that saves the state on shutdown

We will want to create/add to this file when a shutDown request is triggered. This is possible is we use the shutDown message

The following is added to the stack script-

on shutdown

  --set default folder to writeable directory on mobile

  set the defaultFolder to specialFolderPath("Documents")

  --puts the name of the current card into a text file called mobiletest.txt

  put the short name of this card into URL ("file:mobiletest.txt")

  pass shutdown

end shutdown



Load this state from the text file

Load this state from the text file

Now that we have saved the state, we will want to load it when the stack is opened. We can do this with the openStack message-

Again, on the stack script, add the following

on openStack

  --set default folder to folder with text file in it

  set the defaultFolder to specialFolderPath("Documents")

  -- places the contents of this text file into a temp variable

  put URL ("file:mobiletest.txt") into tState

  --navigates to the card names in the temp variable

  go card tState

end openStack

Deploy to device/sim

Deploy to device/sim

Now when you deploy to a device/sim, exit the app and then re-open the last card that you navigated to will be the one show.

Although this is a very basic example, the same principles can be applied to content within an application as well (e.g. text fields, button states, control positions etc)




Tom B.

Thanks for this tutorial. How would you save an array containing a wide range of state information from the app? Can an array be saved as a file or is it better to store it in the cprop of a stack?

Elanor Buchanan

Hi Tom

You can use the arrayEncode function to serialise an array as binary data which you can then save out to file. When you want to read it in again use arrayDecode to convert the binary data back to an array.

There is also a lesson on reading and writing to files at

Kind regards


Add your comment

E-Mail me when someone replies to this comment