Can't figure out why my following code is broken
I've got MainActivity class:
public class MainActivity implements PresenterListener {
...
private Presenter presenter = new Presenter(this);
...
}
Presenter:
public class Presenter extends PresenterUtils {
protected DateTimeFormatter dateFormat = DateTimeFormat.forPattern(getDateFormat());
}
PresenterUtils:
public class PresenterUtils extends Utils {
public String getDateFormat() {
return getResources().getString(R.string.date_format);
}
}
Utils extends AppCompatActivity, so context has to be available for this class. But its not. I mean, IDE allows me to apply getResources()
method, but I've got an exception right after launching:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{...} java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
Exception points to getResources().getString(R.string.date_format)
But! If I apply application context
public class PresenterUtils extends Utils {
public String getDateFormat() {
return ContextProvider.getContext().getResources().getString(R.string.date_format);
}
}
where ContextProvider is
public class ContextProvider extends Application {
private static ContextProvider instance;
public ContextProvider() {
instance = this;
}
public static Context getContext() {
return instance;
}
}
everything is fine
Why is that?