У меня проблемы с использованием SharedPreferences в моем приложении Kivy (Python) для Android. Основная проблема заключается в том, что использование SharedPreferences вызывает сбой приложения. Я имею в виду, что мое приложение не может даже запуститься или сделать сообщение об ошибке, поэтому я не имею ни малейшего представления, что это может быть.
Есть мой main.py:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.metrics import dp, sp, pt
from kivy.properties import ObjectProperty, NumericProperty, StringProperty, BooleanProperty, ListProperty
from kivy.storage.jsonstore import JsonStore
from kivy.uix.textinput import TextInput
from kivy.uix.screenmanager import SlideTransition
from kivy.uix.screenmanager import NoTransition
from kivymd.theming import ThemeManager
from kivymd.toast.kivytoast import toast
from kivymd.textfields import MDTextField
from kivymd.label import MDLabel
import jnius
class keyinput(MDTextField):
pass
class Manager(ScreenManager):
def __init__(self, **kwargs):
super(Manager, self).__init__(**kwargs)
try:
PythonActivity = jnius.autoclass('org.renpy.android.PythonActivity')
activity = PythonActivity.mActivity
cntxt = activity.getApplicationContext()
prefs = cntxt.getSharedPreferences("MY_PREFS", cntxt.MODE_PRIVATE )
myVar = prefs.getString("keyvalue", "Default String")
except jnius.jnius.JavaException as err:
myVar="Error Loading Prefs."
print("KIVY, 3, error: {}".format(repr(err)))
registeredkey = myVar
if registeredkey != '12345678':
self.transition = NoTransition()
self.current = 'login_screen'
else:
self.transition = NoTransition()
self.current = 'main_menu'
class LoginScreen(Screen):
def keycheck(self):
if self.kinput.text == '12345678':
try:
PythonActivity = jnius.autoclass('org.renpy.android.PythonActivity')
activity = PythonActivity.mActivity
cntxt = activity.getApplicationContext()
prefs = cntxt.getSharedPreferences("MY_PREFS", cntxt.MODE_PRIVATE)
editor = prefs.edit()
editor.putString("keyvalue", str(self.kinput.text))
editor.commit()
except Exception as err:
print("\tKIVY, 6, error: {}".format(repr(err)))
toast('KEY IS CORRECT')
self.manager.transition = SlideTransition(direction='left', duration = .17)
self.manager.current = 'main_menu'
elif len(self.kinput.text) > 8:
toast('Too much text!')
else:
toast('KEY IS INCORRECT!')
class MainMenu(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
kinput = ObjectProperty(None)
self.menu_items = [
{
"viewclass": "MDMenuItem",
"text": "text%d" % i,
"callback": self.callback,
}
for i in range(1, 3)
]
self.menu_button = None
def change_variable(self, value):
print("\nvalue=", value)
self.VARIABLE = value
print("\tself.VARIABLE=", self.VARIABLE)
def callback(self, *args):
toast(args[0])
class MainApp(App):
title = "KivyMD Demo and test app for new programms"
theme_cls = ThemeManager()
def build(self):
return Manager()
if __name__ == "__main__":
MainApp().run()
Таммой main.kv:
#:import MDDropdownMenu kivymd.menus.MDDropdownMenu
#:import MDRaisedButton kivymd.button.MDRaisedButton
#:import MDLabel kivymd.label.MDLabel
<OptionalLabel@MDLabel>:
halign: 'center'
font_size: dp(12)
<MDRB@MDRaisedButton>:
size_hint: None, None
size: 3 * dp(48), dp(48)
pos_hint: {'center_x': 0.5, 'center_y': 0.5}
opposite_colors: True
<keyinput>:
size_hint_x: 0.5
halign: 'center'
pos_hint: {'center_x': .5, 'center_y': .5}
max_text_length: 8
<Manager>:
LoginScreen:
id: login_screen
name: 'login_screen'
MainMenu:
id: main_menu
name: 'main_menu'
<LoginScreen>:
kinput: kinput
AnchorLayout:
anchor_y: 'center'
BoxLayout:
orientation: 'vertical'
size_hint: 0.5, 0.5
pos_hint: {'center_x': 0.5, 'center_y': 0.5}
spacing: dp(10)
MDRB:
text: 'Login'
on_release:
root.keycheck()
keyinput:
id: kinput
hint_text: "Login password"
<MainMenu>:
AnchorLayout:
anchor_y: 'center'
BoxLayout:
orientation: 'vertical'
size_hint: 0.5, 0.5
pos_hint: {'center_x': 0.5, 'center_y': 0.5}
spacing: dp(10)
OptionalLabel:
text: 'You have logged in'
Спасибо за внимание и за дальнейшую помощь!