1

I have created a Shopper class which extends Application class for my project. 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. 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).

Pang
  • 9,564
  • 146
  • 81
  • 122
Ajil O.
  • 6,562
  • 5
  • 40
  • 72

2 Answers2

1

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();
Nguyễn Trung Hiếu
  • 2,004
  • 1
  • 10
  • 22
0
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.

Parth Vora
  • 19
  • 4