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.

Python Mobile course

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.

Must read:

Source code

Get updates Follow @aron-bordin
Star it: Star
Contribute: Fork
Download: Download

II - Index

Available tutorials:

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:

You can use any of these storage in the same way.

To create a DictSore, use:

from import DictStore
from os.path import join

data_dir = getattr(self, 'user_data_dir') #get a writable path to save the file
store = DictStore(join(data_dir, 'user.dat'))

To create a JsonStore, use:

from import JsonStore
from os.path import join

data_dir = getattr(self, 'user_data_dir') #get a writable path to save the file
store = JsonStore(join(data_dir, 'user.json'))

Or, to connect to a Redis database, use:

from import RedisStore

params = dict(host='localhost', port=6379, db=14)
store = RedisStore(params)

After creating the store object, any storage will have the same methods.

V - Saving data

To save the user score, you can use:

store.put('score', best=50)

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:

{'score': {'best': 50}}

VI - Getting user data

Before get some data, we need to check if the user has this information saved:

if store.exists('score'):
	best =  store.get('score')['best']

You can read the full doc and check all methods available.

That’s it. Thanks for reading!

Aron Bordin

Aron Bordin

Aron Bordin
Computer Science Student and AI researcher. Always coding something fun :)

[Tutorial] Android Material Icon Library

### Welcome!In this post, I'll show you how to use [Material Icon Library]( is a really...… Continue reading