java - Shared preference failing to find already created keys -
the following code piece of code handles presistence of 2 vars in sharedpreference. when run app first time, save vars' values.(editor.commit returned true). when quit app , restart, settings.contains failing find 2 vars/keys created on first run, in shared preferences.as result app creating values, not supposed (going else condition).
@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); sharedpreferences settings = preferencemanager.getdefaultsharedpreferences(this); sharedpreferences.editor editor=settings.edit(); if (settings.contains("passug1")) passug1=settings.getstring("passug1",""); else { sendjson1(); editor = settings.edit(); //sendjson1(); editor.putstring("passug1", passug1); if (editor.commit()) system.out.println("successfully saved"); else system.out.println("not saved"); //editor.apply(); } if (settings.contains("passug2")) passug2=settings.getstring("passug2",""); else { sendjson2(); editor = settings.edit(); //sendjson2(); editor.putstring("passug2", passug2); if (editor.commit()) system.out.println("successfully saved"); else system.out.println("not saved"); //editor.commit(); //editor.apply(); }
after testing code, appears me reason why nothing being saved preferences because passug1
, passug2
fields null , therefore saving null values preferences. passing null values putstring
delete existing values key. if sendjson1()
, sendjson2()
methods intended assign value passug1
, passug2
should check see if operating correctly.
secondly, using system.out.println
in code not output in normal logcat android log system might making difficult determine if code working or not. should use methods in android.util.log
class in order logging.
finally, initial call settings.edit()
redundant.
Comments
Post a Comment