简体   繁体   English

getApplicationContext()在应用程序类中返回null

[英]getApplicationContext() returns null in Application class

I have created a Shopper class which extends Application class for my project. 我创建了一个Shopper类,该类为我的项目扩展了Application类。 This is how I am trying to get context in the class 这就是我试图在课堂上获得上下文的方式

public class Shopper extends Application {
    private Context context;

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

    public Context getContext() {
        return context;
    }
}

But getApplicationContext always returns null . 但是getApplicationContext始终返回null Am I missing something? 我想念什么吗? I have looked at this and this to get an idea on how to do it; 我已经看过 件事 ,以了解如何做。 but still the same result. 但结果还是一样。

I have added the name of the class to the manifest. 我已将类的名称添加到清单中。

<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>

EDIT 编辑

Correct me if I am wrong (I might be probably), but I don't understand how having the field context as static can affect the value of getApplicationContext (this is what most answers are pointing out). 如果我做错了,可以纠正我(可能是这样),但是我不明白将字段context设为静态会如何影响getApplicationContext的值(这是大多数答案所指出的)。

You must use static 您必须使用静态

public class Shopper extends Application {
private static Context context;

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

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

And use 并使用

Shopper.getContext();
private static Application _instance;
public static Application getAppContext() {
        return _instance;
    }
@Override
public void onCreate() {
    super.onCreate();
   _instance = this;
}

Now you can easily use getAppContext method in whole app all classes to get application context. 现在,您可以轻松地在整个应用程序的所有类中使用getAppContext方法来获取应用程序上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM