2016-03-27 3 views
-2

が把握できない状況が利用できない私は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; 
    } 
} 

すべてがうまくなっている

を適用した場合それはなぜですか?

+0

'getResources()の実装は' PresenterUtils.getResources() 'で何をしますか? –

+0

@GeorgeMulliganどういう意味ですか?コードで指定したとおりにstrings.xmlから文字列を抽出する必要があります。getResources()。getString(R.string.date_format); – Anton

+0

あなたの 'Utils'クラスの定義は、どういうものですか?私はなぜ 'getResources()'コールがそこから有効であるのか分からないので、これを求めています。なぜなら、その呼び出しのために 'Context'が必要なためです。 'Utils'は何かを拡張しているのですか、あるいはあなた自身でその方法を実装しましたか? –

答えて

1

AppCompatActivityから拡張することは、コンテキストを持つことを意味しません。それはアクティビティとしても作成する必要があります。作成したオブジェクトは別のオブジェクトになります。

この場合、明らかにPresenterUtils (Presenter)クラスが手動で初期化されています。したがって、このクラスにContextを渡して代わりに使用する必要があります。

public class PresenterUtils extends Utils { 

    private Context context; 

    public PresenterUtils(Context context) { 
     this.context = context; 
    } 

    public String getDateFormat() { 
     return context.getResources().getString(R.string.date_format); 
    } 
} 
+0

AppCompatActivityを拡張しているMainActivityがすでにコンテキストを持っている理由を教えてください。私は自分自身のためにアンドロイドを再発見しようとしていると思う。 – Anton

+0

MainActivityはアクティビティとしてシステムによって作成される。その場合、アクティビティコンテキストはシステムによって作成され、MainActivityに渡されます。キーは、 "アクティビティとしてシステムによって作成する必要がある"か、内部にコンテキストが存在しないことです。 – nuuneoi

+0

新しいことを学ぶのはとても素晴らしいことです。ありがとうございました! – Anton

関連する問題