Get application context from non activity singleton class
Update: 06-Mar-18
Use MyApplication
instance instead of Context
instance. Application
instance is a singleton context instance itself.
public class MyApplication extends Application {
private static MyApplication mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = this;
}
public static MyApplication getContext() {
return mContext;
}
}
Previous Answer
You can get the the application context like this:
public class MyApplication extends Application {
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
public static Context getContext() {
return mContext;
}
}
Then, you can call the application context from the method MyApplication.getContext()
Don't forget to declare the application in your manifest file:
<application
android:name=".MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name" >
Get Context in non-activity class multiple times
Change
this.cntxt = context;
To
cntxt = context.getApplicationContext();
instead. Where cntxt
is a static context. It will not create activity leak, since it uses application context.
It is better if you learn about background service in Android
https://developer.android.com/training/run-background-service/create-service.html
Getting application context in a non-activity class to pass a CSV file
You need to give the Context of Activities
loadCategory(0); - > loadCategory(0, this);
like this fix the code :
1.
public void loadCategory(int categoryIndex, Context context) {
...
ToolsCategory cat = ToolsSource.getInstance(context).getCategory(categoryIndex);
2.
public static ToolsSource getInstance(Context context) {
if (instance == null) {
try {
instance = new ToolsSource(context);
} catch (IOException e) {
e.printStackTrace();
}
}
return instance;
}
3.
public ToolsSource(Context context) throws IOException {
int i;
mCategory = new ToolsCategory[CATEGORIES.length];
for (i = 0; i < CATEGORIES.length; i++) {
mCategory[i] = new ToolsCategory(CATEGORIES[i], context);
}
}
4.
public ToolsCategory(String name, Context context) throws IOException {
this.context = context;
AssetManager assetManager = context.getAssets();
categoryName = name;
mTools = new Tool[TOOLS_PER_CATEGORY];
assignValues(categoryName, assetManager);
}
android: how to use getApplication and getApplicationContext from non activity / service class
The getApplication()
method is located in the Activity
class, that's why you can't access it from your helper class.
If you really need to access your application context from your helper, you should hold a reference to the activity's context and pass it on invocation to the helper.
Getting raw resource (sound) in non-activity class
You can have a Singleton holding an Application Context
(NOT Activity context) but practically you have to set this context before you use your singleton which can be enforced by throwing exceptions. See below example code.
public class GameSounds {
private static Context sContext;
public static void setContext(Context context) {
if (context == null) {
throw new IllegalArgumentException("context cannot be null!");
}
// In order to avoid memory leak, you should use application context rather than the `activiy`
context = context.getApplicationContext();
if (context == null) {
throw new IllegalArgumentException("context cannot be null!");
}
sContext = context;
}
private static Context getContext() {
if (sContext != null) {
return (Context)sContext;
}
throw new IllegalStateException("sContext was not set yet! Please call method setContext(Context context) first.");
}
// the rest of other methods. e.g. playSounds()
private static GameSounds gameSounds = new GameSounds();
private GameSounds() {
}
public static GameSounds getInstance() {
return gameSounds;
}
public void playSound() {
Context context = getContext();
soundPlayer = MediaPlayer.create(context, mySoundId);
soundPlayer.start();
}
}
Which android context should i use in singletons?
What you pass in does not matter much. What you use should be the Application
context:
public static Database getInstance(Context context) {
if (Database.instance == null)
instance = new Database(context.getApplicationContext());
return instance;
}
Now, if you want to force the caller to supply the Application
, you could do that:
public static Database getInstance(Application context) {
if (Database.instance == null)
instance = new Database(context);
return instance;
}
Personally, I like to consider that an implementation detail, hidden by the API.
The Application
is a global object, created when the process is created. Therefore it is "pre-leaked", in effect. You cannot leak it further. Other types of Context
(e.g., Activity
), referenced from some singleton, may result in memory leaks.
See Dave Smith's epic blog post on the roles of different Context
objects for more.
Context inside non activity class
public Example(Context context){
this.context = context.getApplicationContext();
}
why? use
this.context = context;
instead.
or
wifihist = new wifiHistoryDatabaseHandler(getActivity());
The context variable in telnet class is null.
You can consider to pass context directly in the constructor of Telnet async task
public Telnet(Context c)
{
mContext = c;
}
Context inside non activity class
public Example(Context context){
this.context = context.getApplicationContext();
}
why? use
this.context = context;
instead.
or
wifihist = new wifiHistoryDatabaseHandler(getActivity());
The context variable in telnet class is null.
You can consider to pass context directly in the constructor of Telnet async task
public Telnet(Context c)
{
mContext = c;
}
Related Topics
Differencebetween ? and Object in Java Generics
How to Change Webservice Url Endpoint
How to Allow Users to Check for the Latest App Version from Inside the App
Android Data Binding Using Include Tag
How Does Facebook Add Badge Numbers on App Icon in Android
Android - How to Take Screenshot Programmatically
How to Use Jsp/Jstl to Generate Dynamic CSS/JavaScript Files
Unobtrusive Way to Combine and Compress JavaScript/CSS for Java/Spring/Maven Applications
How to Clear the (Css) Visited History of an Android Webview
Selenium Webdriver - Getcssvalue() Method
Get Filepath and Filename of Selected Gallery Image in Android
Google Firebase Check If Child Exists
Is Custom Enum Serializable Too