0

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.

Siddharth Venu
  • 1,318
  • 13
  • 26

3 Answers3

2

Because fields are initialized to their default values before the constructor runs. Your audioManager field initialization depends on context which is only initialized in constructor.

You should move the audioManager initialization to your constructor if it depends on a constructor argument.

Apparently your getContext() returns a Context that is valid at field initialization phase.

See also: Are fields initialized before constructor code is run in Java?

Community
  • 1
  • 1
laalto
  • 150,114
  • 66
  • 286
  • 303
1

According to prosperK's comment, what you are doing is creating and initializing the variable at the same time. That means context is still null when you created audioManager Variable.

One work around is initialize the audioManager in the contructor when your context will actually have a value.

Mohammed Atif
  • 4,383
  • 7
  • 28
  • 57
  • But I have `context` as a global variable, whose value I set to be equal to the local variable `context`. Why would the global `context`'s value be null? – Siddharth Venu Aug 11 '16 at 10:41
  • 1
    Your global variable will remain null unless you provide it with some value. Value is given in constructor. So, unless constructor is called its null. The fact is your global variables context and audioManager are created at the same time that is you are using same null context to initialize audioManager – Mohammed Atif Aug 11 '16 at 10:43
  • Thank you do much. Got it :) – Siddharth Venu Aug 11 '16 at 10:46
1

initialize audioManager in constructor.

Ramit
  • 416
  • 3
  • 8