Java getApplicationContext()在应用程序类中返回null
我已经为我的项目创建了一个Java getApplicationContext()在应用程序类中返回null,java,android,Java,Android,我已经为我的项目创建了一个购物者类,它扩展了应用程序类。这就是我试图在课堂上了解上下文的方式 public class Shopper extends Application { private Context context; @Override public void onCreate() { super.onCreate(); context = getApplicationContext(); } public
购物者
类,它扩展了应用程序
类。这就是我试图在课堂上了解上下文的方式
public class Shopper extends Application {
private Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
public Context getContext() {
return context;
}
}
但是getApplicationContext
总是返回null
。我错过什么了吗?我已经看过并想知道怎么做;但结果还是一样
我已将类的名称添加到清单中
<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>
编辑
如果我错了,请纠正我(我可能错了),但我不明白将字段
上下文作为静态字段会如何影响getApplicationContext
(这是大多数答案都指出的)。必须使用静态
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();
现在,您可以在整个应用程序的所有类中轻松地使用getAppContext方法来获取应用程序上下文。我试过了。不起作用。同样的结果。为什么你需要这样的背景?如果在manifest中定义了应用程序类,则上下文将在所有活动中可用。trycontext=this.getApplicationContext()代码>@IntelliJAmiya编号):。我将假设项目中出现了一些问题。我正在重新做这个项目again@AjilO. 这样更好。往前走。我已经试过了。同样的结果getApplicationContext
返回null
您的代码不使用静态。无法调用方法getContext();在我发布的代码中,它没有显示我使用了静态
;但我第一次尝试使用的是static,它对我不起作用。
private static Application _instance;
public static Application getAppContext() {
return _instance;
}
@Override
public void onCreate() {
super.onCreate();
_instance = this;
}