I have defined my own Array Adapter class called WordAdapter. Here is my code
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);
The above code produces a Null Pointer Exception.
But this code does not:
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);
Why does the context passed through the constructor not work?
EDITI call it in different activities, one of it is given below:
itemsAdapter = new WordAdapter(this, words, R.color.category_numbers);
where itemsAdapter
is declared as a WordAdapter
and words
is a ArrayList of Word
class items.