Access Application class from class other then Activity
In my application I need data which is accessible for a few activities. I've read that a good solution is to use Application
class for this. So I use it like this:
public class MyApplication extends Application {
private String str;
public String getStr(){
return str;
}
public void setStr(String s){
str = s;
}
}
and I can access this variable from activity like this:
MyApplication appState = ((MyApplication)getApplicationContext());
String str = appState.getStr();
It's ok, but I also have xml parser class:
public class MyXMLHandler extends DefaultHandler {
and if I try to do the same here
MyApplication app = ((MyApplication)getApplicationContext());
String str = app.getStr();
I'm getting The method getApplicationContext() is undefined for the type MyXMLHand开发者_StackOverflowler
How can I access my variable?
Well, usually an XML parser class should be independent of any special context. That means a developer should be able to use it no matter whether he's developing an application or a service or library or whathever.
The XML parser class should not make any assumptions as to the context it is being used in and where it gets parameters from (you'd restrict your parser to function only if it has access to an Application
instance). The parser should not fetch its parameters, the parameters should be set by the caller.
You wouldn't want your XML parser class to show messages to the user, either, would you? Right: "What does an XML parser have to do with user interfaces?" Instead, you'd throw exceptions and make sure they are handled properly, for example depending on whether there's a user interface or not (logging).
So what you'd do is pass the parameters you need when constructing an instance of your XML parser. But you do not pass your application instance as a parameter (think again of dependencies), but you pass the necessary parameters from your application class.
In your example above:
MyApplication app = ((MyApplication)getApplicationContext());
MyXmlHandler handler = new MyXmlHandler(app.getStr());
You should really make sure to keep "tool stuff" separate from anything that would prevent you from using it universally. What would happen if you wanted to use your XML Parser class in another project where your parameter is not provided by the application context but some other class?
I'm sure that you can have a week-long discussion about object-oriented design and how things should be done - but that's basically how I'd do it...
精彩评论