Skip to content Skip to sidebar Skip to footer

Save Variables In Kivy Android With JsonStore

I want to save a variable (label.text) in kivy for an android app and when the App restarts it should load the variable back into label.text. I tried to use JsonStore to save the v

Solution 1:

The error is a bit generic but it seems that you have invalid JSON. Your JSON should be similar to:

{"tito": {"score": "3"}}

You can use __init__ method in your Test class to load the Json at start, i thing that it is most simple than use on_start method in this case.

On the other hand, you need test if JSON file and key exist before try to get it. Otherwise, you can recibe a KeyError exception. You can use try-except for this.

from kivy.app import App
from kivy.storage.jsonstore import JsonStore
from kivy.uix.boxlayout import BoxLayout
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.properties import ObjectProperty

kv_text = '''\
<Test>:
    orientation: "vertical"
    label: label
    BoxLayout:
        Label:
            id: label
            text: '0'
            color: 0,0,0,1
            pos: 250,200
            size: 50,50
            font_size:30
        Button:
            text: 'save'
            on_release: root.save()
        Button:
            text: 'load'
            on_release: root.load()

    Button:
        size_hint: 1, .5
        text: 'click me'
        on_press: label.text = str(int(label.text)+1)
'''

class Test(BoxLayout):
    label = ObjectProperty()
    Window.clearcolor = (1, 1, 1, 1)

    def __init__(self, **kwargs):
        super(Test,  self).__init__(**kwargs)
        self.store = JsonStore('hello.json')
        self.load()

    def save(self):
        self.store.put('tito', score= self.label.text)

    def load(self):
        try:
            self.label.text = self.store.get('tito')['score']
        except KeyError:
            pass


class MyApp(App):
    def build(self):
        Builder.load_string(kv_text)
        return Test()


if __name__ == '__main__':
    MyApp().run()

Post a Comment for "Save Variables In Kivy Android With JsonStore"