が把握できない状況が利用できない私はMainActivityクラスを持っている:カスタムクラスはAppCompatActivityを拡張:getResources()はIDEで認識されているが、私の次のコードは、</p> <p>壊れている理由
public class MainActivity implements PresenterListener {
...
private Presenter presenter = new Presenter(this);
...
}
プレゼンター:
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はAppCompatActivityを拡張しているため、このクラスではコンテキストが利用可能でなければなりません。しかし、そうではありません。私が意味する、IDEは私がgetResources()
方法を適用することができますが、私は右の起動後に例外を持っている:
java.lang.RuntimeException:活動 ComponentInfo {...}のjava.lang.NullPointerExceptionをインスタンス化することができません。 :
getResources().getString(R.string.date_format)
に 仮想メソッド 'android.content.res.Resources android.content.Context.getResources()' nullのオブジェクト参照の
例外ポイントを呼び出すための試みしかし!私は、アプリケーションコンテキスト
public class PresenterUtils extends Utils {
public String getDateFormat() {
return ContextProvider.getContext().getResources().getString(R.string.date_format);
}
}
ContextProviderが
public class ContextProvider extends Application {
private static ContextProvider instance;
public ContextProvider() {
instance = this;
}
public static Context getContext() {
return instance;
}
}
すべてがうまくなっている
を適用した場合それはなぜですか?
'getResources()の実装は' PresenterUtils.getResources() 'で何をしますか? –
@GeorgeMulliganどういう意味ですか?コードで指定したとおりにstrings.xmlから文字列を抽出する必要があります。getResources()。getString(R.string.date_format); – Anton
あなたの 'Utils'クラスの定義は、どういうものですか?私はなぜ 'getResources()'コールがそこから有効であるのか分からないので、これを求めています。なぜなら、その呼び出しのために 'Context'が必要なためです。 'Utils'は何かを拡張しているのですか、あるいはあなた自身でその方法を実装しましたか? –