为什么getContext()工作但通过构造函数传入的上下文不起作用?

时间:2016-08-11 10:34:14

标签: android android-studio nullpointerexception

我已经定义了自己的名为WordAdapter的Array Adapter类。这是我的代码

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);

上面的代码产生一个空指针异常。

但是这段代码没有:

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);

为什么通过构造函数传递的上下文不起作用?

编辑我在不同的活动中称呼它,其中一个在下面给出:

itemsAdapter = new WordAdapter(this, words, R.color.category_numbers);

其中itemsAdapter被声明为WordAdapterwordsWord类项目的ArrayList。

3 个答案:

答案 0 :(得分:2)

因为字段在构造函数运行之前初始化为其默认值。您的audioManager字段初始化取决于contextaudioManager仅在构造函数中初始化。

如果它取决于构造函数参数,则应将getContext()初始化移动到构造函数。

显然,您的Context会返回在字段初始化阶段有效的public class InstagramList extends Activity { ListView list; String[] web = { "Kyary Pamyu Pamyu", "Tokyo Girls' Style", "Haruka Nakagawa", "Nemu Yumemi", "Moga Mogami", "Ayane Fujisaki", "Koda Kumi", "Atsuko Maeda", "Tomomi Itano", "Haruna Kojima", "Utada Hikaru", "Shibasaki Ko", "Taeyon", "Tiffany", "Jessica", "Sooyoung", "Sunny", "Laboum", "YeEun", "Yubin", "Hyelim" }; Integer[] imageId = { R.drawable.kyary, R.drawable.tgs, R.drawable.haruka, R.drawable.nemu, R.drawable.moga, R.drawable.ayane, R.drawable.koda, R.drawable.atsuko, R.drawable.tomomi, R.drawable.haruna, R.drawable.utada, R.drawable.shibasaki, R.drawable.taeyon, R.drawable.tiffany, R.drawable.jessica, R.drawable.sooyoung, R.drawable.sunny, R.drawable.laboum, R.drawable.yeeun, R.drawable.yubin, R.drawable.hyelim }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.instagram_main); CustomList adapter = new CustomList(InstagramList.this, web, imageId); } }

另请参阅:Are fields initialized before constructor code is run in Java?

答案 1 :(得分:1)

根据prosperK的评论,您正在做的是同时创建和初始化变量。这意味着当您创建audioManager变量时,上下文仍为空。

当你的上下文实际上有一个值时,一个解决方法就是在构造函数中初始化audioManager。

答案 2 :(得分:1)

在构造函数中初始化audioManager。