gpt4 book ai didi

java - 应用程序子类中的奇怪异常

转载 作者:行者123 更新时间:2023-12-01 21:27:39 25 4
gpt4 key购买 nike

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

最佳答案

mSounds.get(resourceId);当 HashMap 中不存在该键时返回 null。因此出现空指针异常。

要解决这个问题,你需要做这样的事情。

int soundId = -1;

Integer tempSoundId = mSounds.get(resourceId);
if(tempSoundId != null)
soundId = tempSoundId;

This is an expected java behaviour since we are trying to unbox a null value.

关于java - 应用程序子类中的奇怪异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37843694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com