Python for Android Tutorial #6 – Saving and reading user data
This is the sixth post about mobile development with Python.
In this post, we’ll see how to save and read user data with Kivy. It’s compatible with Desktop, Android and iOS.
I - About the Tutorials
I’ll show you how to use each mobile API, like compass, camera, sensors, sound, and others. After the API, we will start to test some Python libs, as PyGame and OpenCV. I’m using Android with buildozer, but major part are compatible with iOS as well.
|Get updates||Follow @aron-bordin|
II - Index
- Tutorial #1 - Accelerometer
- Tutorial #2 - Camera
- Tutorial #3 - Kivy Designer
- Tutorial #4 - Debug
- Tutorial #5 - Android and iOS game with Python
- Tutorial #6 - Reading and saving user data
- Tutorial #7 - Use Android classes with PyJNIus
III - About this tutorial
It’s a shot tutorial, I’ll show you how to save user data with Kivy.
We’ll be using Kivy Storage, you can save user settings, score, or anything else inside files, so Python and Kivy will easily manage these files for you.
It’s explaining more about the game created at Tutorial #5 - Android and iOS game with Python
When I wrote this post, I was using Kivy 1.9.0, and this API was experimental, and the API was subject to change in a future version. So, if you are using a new version of Kivy and something is not working fine, just let me know.
IV - About Kivy Storage
We can save user information in these ways:
- kivy.storage.dictstore.DictStore: use a python dict as a store
- kivy.storage.jsonstore.JsonStore: use a JSON file as a store
- kivy.storage.redistore.RedisStore: use a Redis database with redis-py
You can use any of these storage in the same way.
To create a DictSore, use:
To create a JsonStore, use:
Or, to connect to a Redis database, use:
After creating the store object, any storage will have the same methods.
V - Saving data
To save the user score, you can use:
This code will create the key score and set the best as 50. You can change the key score to any name, and the content best to any name.
If using a JsonStore, you’ll have the following file:
VI - Getting user data
Before get some data, we need to check if the user has this information saved:
You can read the full doc and check all methods available.
That’s it. Thanks for reading!