开发者

Android: this.getApplication() returns NULL pointer

开发者 https://www.devze.com 2022-12-08 06:45 出处:网络
I\'m running the following line in an Activity, which is within the same application, but in a different package:

I'm running the following line in an Activity, which is within the same application, but in a different package:

AppObject appObj = (AppObject)this.getApplication();
// FYI: A开发者_开发百科ppObject is my extension class of Application.

It returns only a null pointer, while when I move it to the "main" package and run it from there it returns the application reference as expected.

I've defined the activity in my AndroidManifest.xml with the full qualified class name, since it is in another package: <activity android:name="com.foo.bar.TestActivity"></activity>


Update: As suggested in a question below android:name="AppObject" was already in the <application> tag of the AndroidManifest.xml


It's important to call getApplication() in the activity's onCreate() method, not in the constructor.


You need the update application tag to AndroidManifest.xml with your class name, which is extended from Application, with proper package name.

<application android:name=".AppObject">


As per Application tag google docs, Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.

here


Just run into the same thing, having refactored all my code still got the same issue, noticed that I was setting the local mApplication variable in the constructor, it should go in the onCreate(), I think all the objects in the manifest may be constructed first before getApplication() is setup so you need to call getApplication() in or after onCreate() has been called. Haven't refactored all my code back again to see if this works for different packages (sigh).


I think, it isn't a null pointer, but your function which you want to use next in the class AppObject maybe wrong.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号