Android java : null context in a class that extend Application -
i have class extending application. when try context of class either using "getapplicationcontext" or using "getbasecontext", context allways null.
i need context use "getsharedpreferences".
the error printed :
caused by: java.lang.nullpointerexception @ android.content.contextwrapper.getapplicationcontext(contextwrapper.java:109)
what doing wrong or other ways can use "getsharedpreferences" without context (if possible) ?
thanks help.
edit code :
i'm initializing class "deviceinfo" in main class. class "deviceinfo" extends application. in it's constructor tried :
protected deviceinfo() { context = getapplicationcontext(); }
wich gives me same error mentioned earlier.
and here main line causing me trouble...
sharedpreferences key = getapplicationcontext().getsharedpreferences("keys", context.mode_private);
final edit : all, took inputs , realized wasn't doing right way @ all. changed code , works, again.
your problem application's context
hasn't been created before you're trying access it. ensure context
has been created, should wait access context
until oncreate()
before attempting access context object.
for example:
public class deviceinfo extends application { @override public void oncreate() { super.oncreate(); sharedpreferences key = getapplicationcontext().getsharedpreferences("keys", context.mode_private); } }
you can use preferencemanager.getdefaultsharedpreferences(getapplicationcontext())
access default preferences file.
Comments
Post a Comment