Crashlytics给我发了一个我不理解的堆栈跟踪,我无法模拟:
Fatal Exception: java.lang.NullPointerException
at lelisoft.com.lelimath.helpers.LeliMathApp.playSound(LeliMathApp.java:81)
at lelisoft.com.lelimath.fragment.PuzzleFragment$HandleClick.onClick(PuzzleFragment.java:158)
at android.view.View.performClick(View.java:4276)
LeliMath是android应用程序子类,只需初始化一次。我明白这是一种单身人士。它失败的代码在创建时初始化,永远不会被取消。
public class LeliMathApp extends Application {
private Map<Integer, Integer> mSounds = new HashMap<>();
private boolean soundEnabled;
public void onCreate() {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
soundEnabled = sharedPref.getBoolean(GamePreferenceActivity.KEY_SOUND_ENABLED, true);
setSoundLevel(sharedPref.getInt(GamePreferenceActivity.KEY_SOUND_LEVEL, 50));
toggleSound(soundEnabled);
}
public void playSound(int resourceId) {
if (soundEnabled) {
int soundId = mSounds.get(resourceId); // NPE here
mShortPlayer.play(soundId, soundLevel, soundLevel, 0, 0, 1);
}
}
public void toggleSound(boolean state) {
log.debug("Toggle sound support");
if (! state && mShortPlayer != null) {
mShortPlayer.release();
mShortPlayer = null;
mSounds.clear();
} else if (state && mShortPlayer == null) {
if (Build.VERSION.SDK_INT >= 23) {
mShortPlayer = new SoundPool.Builder().build();
} else {
//noinspection deprecation
mShortPlayer = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
}
mSounds.put(R.raw.correct, this.mShortPlayer.load(this, R.raw.correct, 1));
mSounds.put(R.raw.incorrect, this.mShortPlayer.load(this, R.raw.incorrect, 1));
mSounds.put(R.raw.victory, this.mShortPlayer.load(this, R.raw.victory, 1));
}
}
它不能在NPE上失败,但确实如此。任何的想法?我很想看到日志,但我不知道用户有这个错误。
更新:这是对此方法的调用列表
LeliMathApp.getInstance().playSound(R.raw.correct);
LeliMathApp.getInstance().playSound(R.raw.incorrect);
LeliMathApp.getInstance().playSound(R.raw.victory);
答案 0 :(得分:3)
mSounds.get(RESOURCEID);当hashmap中不存在键时返回null。因此空指针异常。
要解决这个问题,你需要做这样的事情。
int soundId = -1;
Integer tempSoundId = mSounds.get(resourceId);
if(tempSoundId != null)
soundId = tempSoundId;
这是一种预期的java行为,因为我们正在尝试取消装入null 值。