私は自分のArrayAdapterクラスをWordAdapterという名前で定義しました。ここに私のコードですなぜgetContext()は動作しますが、コンストラクタを介して渡されたコンテキストが機能しないのですか?
Context context;
int backgroundColor;
private MediaPlayer mMediaPlayer = null;
public WordAdapter(Context context, ArrayList<Word> words, int backgroundColor) {
super(context, R.layout.list_item, words);
this.context = context;
this.backgroundColor = backgroundColor;
}
private AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
上記のコードは、Null Pointer Exceptionを生成します。
しかし、このコードではありません:
Context context;
int backgroundColor;
private MediaPlayer mMediaPlayer = null;
public WordAdapter(Context context, ArrayList<Word> words, int backgroundColor) {
super(context, R.layout.list_item, words);
this.context = context;
this.backgroundColor = backgroundColor;
}
private AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
なぜコンストラクタを通過したコンテキストが動作しませんか? WordAdapter
とwords
がWord
クラスアイテムのArrayListにあるようitemsAdapter
が宣言され
itemsAdapter = new WordAdapter(this, words, R.color.category_numbers);
:
EDITは、私はそれの一つが以下に与えられる、様々な活動でそれを呼び出します。
plzはあなたがコンストラクタ – has19
移動 'audioManager =(AudioManager)context.getSystemService(Context.AUDIO_SERVICE)を呼び出しているところ私たちを見る;'ρяσѕρєя[email protected]方法 –
の内側に私はグローバル変数として定義されたコンテキストを。あなたの方法がうまくいかない理由(答えとして)を教えてください。 –