Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java getApplicationContext()在应用程序类中返回null_Java_Android - Fatal编程技术网

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中定义了应用程序类,则上下文将在所有活动中可用。try
context=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;
}