java - Android: Access SharedPreferences from a home widget in another class -
i have activity runs method in class access sharedpreferences. want make widget can run same method button click. works long app open in background, if closed, app crashes when press button on widget.
i because of context need access sharedpreferences, , tried passing context through activity , widget separately not working.
basically, how can access sharedpreferences widget when method in class?
activity code:
public class mainactivity extends appcompatactivity { protected static context context; sharedpreferences prefs; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mainactivity.context = getapplicationcontext(); } public void panicfromview(view view){ prefs = preferencemanager.getdefaultsharedpreferences(context); methods.panic(prefs); } }
widget code:
public class panicwidget extends appwidgetprovider { public static final string click_panic = "panic"; sharedpreferences prefs; @override public void onupdate(context context, appwidgetmanager appwidgetmanager, int[] appwidgetids) { remoteviews remoteviews = new remoteviews(context.getpackagename(), r.layout.panic_widget); intent intent = new intent(context, panicwidget.class); intent.setaction(click_panic); pendingintent actionpendingintent = pendingintent.getbroadcast(context, 0, intent, 0); remoteviews.setonclickpendingintent(r.id.panicbutton, actionpendingintent); appwidgetmanager.updateappwidget(appwidgetids, remoteviews); prefs = preferencemanager.getdefaultsharedpreferences(context); } @override public void onreceive(context context, intent intent){ super.onreceive(context, intent); if (click_panic.equals(intent.getaction())){ panicfromwidget(prefs); } } public void panicfromwidget(sharedpreferences prefsin){ methods.panic(prefsin); } }
methods:
public class methods { public static context getappcontext() { return mainactivity.context; } public static void panic(sharedpreferences prefsin){ //loops through contacts (int = 1; <= 5; i++) { string contactkey = "contact-sms" + i; string contactno = getcontact(contactkey, prefsin); //sends sms if contact number exists if (!contactno.equals("")) { sendsms(contactno); } } } //returns contact number contact name public static string getcontact(string key, sharedpreferences prefsin){ return prefsin.getstring(key, null); } //sends sms contact number public static void sendsms(string phoneno){ try{ string msg = "test"; smsmanager smsmanager = smsmanager.getdefault(); smsmanager.sendtextmessage(phoneno, null, msg, null, null); toast.maketext(getappcontext(), "sms sent", toast.length_short).show(); } catch (exception ex) {} } }
nevermind, work. somehow sharedpreferences got cleared without me knowing throwing nullpointerexception.
Comments
Post a Comment