Siddharth Venu
Siddharth Venu

Reputation: 1388

Why does getContext() work but context passed in through constructor does not work?

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.

Upvotes: 0

Views: 165

Answers (3)

Mohammed Atif
Mohammed Atif

Reputation: 4513

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.

Upvotes: 1

laalto
laalto

Reputation: 152787

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?

Upvotes: 2

Ramit
Ramit

Reputation: 426

initialize audioManager in constructor.

Upvotes: 1

Related Questions