如何在不获取ResourcesNotFound的情况下检查getResources是否为null

时间:2019-02-10 14:35:55

标签: android null

我有一些声音按照级别进行组织,分别为level1explicacio2,level2explicacio8等。有时这种声音有时会不存在。因此,我需要检查是否存在例如level5explicacio3,如果存在,请播放一些动画。因此,我进行了一次if check检查levelSoundPlayer是否为null,但是,由于它找不到levelSoundPlayer的资源,因此它不会编译。我该如何解决呢?

        levelSound = "level" + sharedPreferences.getString("Level","1") + "explicacio" + Integer.toString(1);


    Log.i("aviam", levelSound);
    levelSoundPlayer = MediaPlayer.create(this, getResources().getIdentifier(levelSound, "raw", getPackageName()));
    imageView = findViewById(R.id.imageView);
    imageViewReplace = findViewById(R.id.imageViewReplace);

    if (levelSoundPlayer!=null){
        Animation a = new AlphaAnimation(1.00f, 0.00f);
        a.setRepeatMode(Animation.REVERSE);
        a.setRepeatCount(Animation.INFINITE);
        a.setDuration(1000);
        imageViewReplace.startAnimation(a);
    }

1 个答案:

答案 0 :(得分:0)

您可以从其标识符中进行检查,如下所示

levelSound = "level" + sharedPreferences.getString("Level","1") + "explicacio" + Integer.toString(1);
        Log.i("aviam", levelSound);
        levelSoundPlayer = MediaPlayer.create(this, getResources().getIdentifier(levelSound, "raw", getPackageName()));
        imageView = findViewById(R.id.imageView);
        imageViewReplace = findViewById(R.id.imageViewReplace);

        int valId = getResources().getIdentifier(levelSound, "raw", getPackageName());
        if (valId != 0){
            Animation a = new AlphaAnimation(1.00f, 0.00f);
            a.setRepeatMode(Animation.REVERSE);
            a.setRepeatCount(Animation.INFINITE);
            a.setDuration(1000);
            imageViewReplace.startAnimation(a);
        }

https://developer.android.com/reference/android/content/res/Resources文档中也说过

  

int关联的资源标识符。如果没有这样的资源,则返回0   被找到。 (0不是有效的资源ID。)