gpt4 book ai didi

java - getApplicationContext() 在 Application 类中返回 null

转载 作者:行者123 更新时间:2023-11-30 00:22:12 27 4
gpt4 key购买 nike

我已经为我的项目创建了一个 Shopper 类,它扩展了 Application 类。这就是我试图在类里面获取上下文的方式

public class Shopper extends Application {
private Context context;

@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}

public Context getContext() {
return context;
}
}

但是 getApplicationContext 总是返回 null。我错过了什么吗?我看过thisthis了解如何去做;但还是一样的结果。

我已将类的名称添加到 list 中。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="vn.com.shopper">

<application
android:name=".Shopper"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/ShopperTheme"
android:fullBackupContent="true">
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

编辑

如果我错了请纠正我(我可能错了),但我不明白将字段 context 设置为静态如何影响 getApplicationContext 的值(这是大多数答案所指出的)。

最佳答案

你必须使用static

public class Shopper extends Application {
private static Context context;

@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}

public static Context getContext() {
return context;
}
}

并使用

Shopper.getContext();

关于java - getApplicationContext() 在 Application 类中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46068034/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com