【发布时间】:2017-09-06 06:14:20
【问题描述】:
我创建了一个 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。我错过了什么吗?我查看了this 和this 以了解如何操作;但结果还是一样。
我已将类的名称添加到清单中。
<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 的值(这是大多数答案所指出的)。
【问题讨论】:
-
我试过了。不工作。结果相同。
-
为什么需要这样获取上下文?如果您在清单中定义了应用程序类,则该上下文将在您的所有活动中可用。
-
试试
context = this.getApplicationContext(); -
@IntelliJAmiya 否):。我将假设项目中出现了问题。我再次重新制作这个项目
-
@AjilO。这样更好。继续前进。