I was finding myself frequently calling getApplication() and casting it as MyApplication so that I could call a method in MyApplication. I decided to declare the static variable Current in MyApplication and set it in the constructor. Now I don't have to do the casting.
Are there any pitfalls to taking this approach?
public class MyApplication extends Application {
public static MyApplication Current;
public MyApplication(){
super();
Current = this;
}
public void doSomething(){
}
}
public class MyActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApplication.Current.doSomething();
}
}
Below is, I think, the normal approach for getting the application and calling the method.
public class MyApplication extends Application {
public void doSomething(){
}
}
public class MyActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MyApplication)getApplication()).doSomething();
}
}