i'm new java. i've made counter goes user holds on button. want app start int value of left. know sharedpreference way go i've no idea how use it. i'm not sure put part of sharedpreference. thank you.
public class mainactivity extends appcompatactivity { button button; int count = 1; textview text; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); button = (button) findviewbyid(r.id.button); text = (textview) findviewbyid(r.id.textview); button.setonlongclicklistener(new view.onlongclicklistener() { @override public boolean onlongclick(view view) { count++; text.settext(string.valueof(count)); return false; } }); }
}
add following function activity
public int getvalue(string key) { sharedpreferences sharedpref = getpreferences(context.mode_private); int value = sharedpref.getint(key, 0); return value; } public void savevalue(string key, int value) { sharedpreferences sharedpref = getpreferences(context.mode_private); sharedpreferences.editor editor = sharedpref.edit(); editor.putint(key, value); editor.commit(); }
some code added in oncreate()
method
final string key = "somekey"; count = getvalue(key); //get value sharedpreference button = (button) findviewbyid(r.id.button); text = (textview) findviewbyid(r.id.textview); text.settext(string.valueof(count)); // set first button.setonlongclicklistener(new view.onlongclicklistener() { @override public boolean onlongclick(view view) { count++; savevalue(key,count); text.settext(string.valueof(count)); return false; } });
Comments
Post a Comment