【问题标题】:getApplicationContext() returns null in Application classgetApplicationContext() 在 Application 类中返回 null
【发布时间】: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。我错过了什么吗?我查看了thisthis 以了解如何操作;但结果还是一样。

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

<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。这样更好。继续前进。

标签: java android


【解决方案1】:

您必须使用静态

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();

【讨论】:

  • 我试过这个。结果相同。 getApplicationContext 返回null
  • 您的代码没有使用 static。你不能调用方法 getContext();
  • 在我发布的代码中并没有显示我使用了static;但是我尝试的第一个link 使用了静态,但它对我不起作用。
【解决方案2】:
private static Application _instance;
public static Application getAppContext() {
        return _instance;
    }
@Override
public void onCreate() {
    super.onCreate();
   _instance = this;
}

现在您可以轻松地在整个应用所有类中使用 getAppContext 方法来获取应用上下文。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    相关资源
    最近更新 更多