How can I get a resource content from a static context?
- Create a subclass of
Application
, for instancepublic class App extends Application {
- Set the
android:name
attribute of your<application>
tag in theAndroidManifest.xml
to point to your new class, e.g.android:name=".App"
- In the
onCreate()
method of your app instance, save your context (e.g.this
) to a static field namedmContext
and create a static method that returns this field, e.g.getContext()
:
This is how it should look:
public class App extends Application{
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = this;
}
public static Context getContext(){
return mContext;
}
}
Now you can use: App.getContext()
whenever you want to get a context, and then getResources()
(or App.getContext().getResources()
).
Is it possible to get resources inside a static context block?
getResources()
(short for ~ MyActivity.this.getResources()
) requires a context object which is not initialized at that time. Since context is only available after you hit onCreate
you can't even do it at construction time of MyActivity
.
The reason is that the activity manager which instantiates your MyActivity
class has to determine the configuration (orientation, screen size, language, ...) before he knows which resources have to be extracted from the xml. -> Resources are not static and can't be accessed from static context.
So I guess there is no way around doing those operations in onCreate
or later.
Edit: While you certainly can update the static HashMap (or a static Context
) from onCreate
I wouldn't recommend that since you can have several instances of the same Activity with possibly different / changing configurations. Also storing a static Context
is a great way to create a Memory Leak
How to get getclass().getResource() from a static context?
It can't compile because getResource
takes a resource name (a String
, and not a File
) as parameter, in order to load a resource using the class loading mechanism (from the classpath). Using it with a File
makes no sense. If you want to open a file, just use a FileInputStream
or a FileReader
.
See http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource%28java.lang.String%29, and include the compiler error message next time you have such a question.
getClass().getResource() in static context
Remove the ".getClass()" part.
Just use
URL u = StaticResource.class.getResource("image.png");
Better way to get static content from resources in android?
My question is which one is better approach to initialize static field?
Neither. Get rid of the static
field.
Your application needs to handle the case where the user changes their language while your process is still running. You need to retrieve this string resource at more appropriate points, so that when you undergo the configuration change, you start using the right string. As it stands, with your implementation (no matter how you populate the static
field), you will never change the language of this string, and therefore the string will be wrong in some cases.
And if the answer is "this string is never being translated", get rid of the string resource and put the string in the Java code as a final static
field.
How to access a file in a static context?
Replace this.getClass()
with the name of your class and class
:
FileInputStream file = (FileInputStream)
YourClass.class.getResourceAsStream("/files/lito.properties");
Also, try to have all the resource files in a proper resources folder rather than in your java src folder. This is because some compilers like maven will ignore any non.java file from sources.
load a resource file in a static method
I assume a compile error. Replace
getClass()
with
DataLoader.class
If I guessed wrong, please explain what error you get and post the corresponding message and/or stacktrace. Please don't add it as comment, the formatting there is horrible for this kind of thing.
Related Topics
C++ Equivalent of Java'S Instanceof
How to Check Internet Access on Android? Inetaddress Never Times Out
Android Update 17 Seems Incompatible With External Jars
Why Retrieving Google Directions For Android Using Kml Data Is Not Working Anymore
Classpath Does Not Work Under Linux
How to Convert a Byte Array to a Hex String in Java
Preparedstatement in Clause Alternatives
Java: Maintaining Aspect Ratio of Jpanel Background Image
Error - Trustanchors Parameter Must Be Non-Empty
Creating a Custom Button in Java With Jbutton
How to Round Up the Result of Integer Division
Setting Singleton Property Value in Firebase Listener
How to Parse Jsonarray in Android
React on Global Hotkey in a Java Program on Windows/Linux/Mac
What Is Reflection and Why Is It Useful