square / mortar

A simple library that makes it easy to pair thin views with dedicated controllers, isolated from most of the vagaries of the Activity life cycle.
Apache License 2.0
2.16k stars 156 forks source link

Dangerous to build scopes in getSystemService? #155

Open rjrjr opened 9 years ago

rjrjr commented 9 years ago

@loganj, didn't you say that this was a bad idea? How come?

https://github.com/square/mortar/blob/master/mortar-helloworld/src/main/java/com/example/hellomortar/HelloApplication.java#L25

loganj commented 9 years ago

Building a root scope this way is fine. It's dangerous to try to access the Application from getSystemService in an Activity, because getSystemService is called when the Activity is not (yet) attached to the Application. At least, that's the behavior I was seeing. I haven't dug into it much.

This is the guard I ended up with:

  @Override public Object getSystemService(String name) {
    if (getApplication() == null) {
      return super.getSystemService(name);
    }
    MortarScope appScope = MortarScope.getScope(getApplication());
   // ...
  }
pyricau commented 9 years ago

Got the same behavior when overriding getResources() and calling getApplication() from there. Ended up with same guard.