java - Android SharedPreferences from onclick in a fragment -
i hoping can give me direction on how access sharedpreferences within button's onclick event defined within onviewcreated event.
i can set values of interface within onviewcreated event calling:
sharedpreferences prefs = this.getactivity().getsharedpreferences( "com.example.app", context.mode_private); and obtaining appropriate values, have button on interface pressed save changes , can't seem come proper way access sharedpreferences within button's click event:
button btn = (button)view.findviewbyid(r.id.btnsave); btn.setonclicklistener(new view.onclicklistener() { public void onclick(view v) { // perform action on click log.d("test","here"); sharedpreferences prefs = this.getactivity().getsharedpreferences( "com.example.app", context.mode_private); } }); this code doesn't work since here referring view , getactivity doesn't work view. can tell me how access activity here can access sharedpreferences?
hi there , welcome stackoverflow.
the reason why can't access sharedpreferences because this not fragment: if closer, you'll realize have 2 nested contexts, this onclicklistener object (that inside fragment).
when need access "parent context", this:
public class mycoolfragment extends fragment { // here "this" in fact fragment, // this.getactivity().getsharedpreferences() exist . . . button btn = (button)findviewbyid(r.id.btnsave); btn.setonclicklistener(new view.onclicklistener() { public void onclick(view v) { // perform action on click // "this" no longer fragment, view.onclicklistener // access parent context prepend class name: // mycoolfragment.this.getactivity().getsharedpreferences work: sharedpreferences prefs = mycoolfragment.this.getactivity().getsharedpreferences() "com.example.app", context.mode_private); } }); it typical in java have deeply-nested contexts, have tell java this want.
also, remember you can context view., inside click handler do:
button btn = (button)view.findviewbyid(r.id.btnsave); btn.setonclicklistener(new view.onclicklistener() { public void onclick(view v) { // perform action on click activity myactivity=(activity)(v.getcontext()); // views have reference context sharedpreferences prefs =myactivity.getsharedpreferences( "com.example.app", context.mode_private); } }); hope helps !
Comments
Post a Comment