安卓; getApplication() 返回 null,不明白为什么

发布于 2024-10-04 17:33:27 字数 602 浏览 0 评论 0原文

(这里已经很晚了,所以可以监督一些非常简单的东西..)

我有以下类:

public class GlobalState extends Application {
    private Stub stub = new Stub();

    public Stub getStub() {
        return stub;
    }
}

这在android清单上的我的应用程序标签中..

<application android:name="com.jameselsey.observerpattern.GlobalState"
...
>

现在,每当我尝试抓住它时,例如在服务类中,我得到一个空指针(gs为空),我正在使用以下内容

private GlobalState gs = (GlobalState) getApplication();
private Stub stub = gs.getStub();

我在另一个应用程序中工作了类似的设置,所以我真的不明白为什么这不起作用,因为我基于此有效的那个。

有什么想法吗?

(It's quite late here, so could be overseeing something really simple..)

I've got the following class :

public class GlobalState extends Application {
    private Stub stub = new Stub();

    public Stub getStub() {
        return stub;
    }
}

and this in my application tag on android manifest..

<application android:name="com.jameselsey.observerpattern.GlobalState"
...
>

Now, whenever I try to grab this, such as in a Service class, I get a null pointer (gs is null), I'm using the following

private GlobalState gs = (GlobalState) getApplication();
private Stub stub = gs.getStub();

I've got a similar setup working in another app, so I really can't see why this isn't working since I've based this on the one that does work.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赠我空喜 2024-10-11 17:33:27

您是否使用您的类名更新了 AndroidManifest.xml 中的应用程序标记?

<application android:name=".AppObject">

您可能会在此处找到一些帮助

Did you update the application tag in AndroidManifest.xml with your class name?

<application android:name=".AppObject">

You might find some help here

云之铃。 2024-10-11 17:33:27

您是否尝试过(GlobalState) getApplicationContext();
这是我使用自己的应用程序类时使用的唯一方法调用。您也可以将名称剪切为 android:name="GlobalState" (至少在 2.2 中)

Have you tried (GlobalState) getApplicationContext();
That's the only method call I use when I use my own application class. You can also just cut the name to android:name="GlobalState" (at least in 2.2)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文