android - Use Shared Preferences inside a fragment -


i want use shared preferences inside fragment. 1 check if fragment run first time , if yes stores value shared preference. don't know why doesn't work. here code.

string user_name; @nullable @override public view oncreateview(layoutinflater inflater, @nullable viewgroup container, @nullable bundle savedinstancestate) {     view view = inflater.inflate(r.layout.item_list_fragment, container, false);      sharedpreferences sp = getactivity().getpreferences(context.mode_private);     sharedpreferences.editor edit = sp.edit();     if(sp.getboolean("isfirst",true)) {         edit.putboolean("isfirst", false);         edit.putstring("first_name", firstrunactivity.username).apply();     }      user_name = sp.getstring("first_name","not workking");      textview test = (textview) view.findviewbyid(r.id.test);      test.settext(user_name);       } 

from code, if did not set value of isfirst true return false

if(sp.getboolean("isfirst",true)) {     edit.putboolean("isfirst", false);     edit.putstring("first_name", firstrunactivity.username).apply(); } 

you can try solution.

first in firstrunactivity, can set class member boolean variable

private boolean infirstactivity = true; 

then in oncreate method, need set sharepreference isfirst key value like

if(infirstactivity) edit.putboolean('isfirst', true); 

then, can check code thereafter in class.

if(sp.getboolean("isfirst",true)) {   edit.putboolean("isfirst", false);   edit.putstring("first_name", firstrunactivity.username).apply(); } 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -