public class SplashScreen extends AppCompatActivity { static MediaPlayer mediaPlayer; public SplashScreen(){ mediaPlayer = MediaPlayer.create(this, R.raw.acdc); mediaPlayer.start(); } } 

on the first line of the constructor, I get Null, with the message that it is impossible to create an instance of the class. I suppose that at the time of the constructor development, the SplashScreen class itself is not fully ready, has not yet been created to transfer itself. After what will it be ready?

    1 answer 1

    The short answer is in the onCreate method.

    Usually an empty and ready-for-all activity looks like this:

     public class ExampleActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); // Вот здесь можно начинать творить } } 

    UPD: Just now noticed. You have static MediaPlayer mediaPlayer; , you shouldn’t do that, better declare the media player as a regular private MediaPlayer mediaPlayer; . If you want your media player to be available longer than your activation life, use the service .

    • Yes, I know what's onCreate. But the question is why it is impossible to pass this in the constructor, in this case, the context is under this. And thanks to the service, I needed the player to live longer than the activation. If I want one song to play at one moment and then the second one starts on the other one, and when I return to the last one, did the first song continue to play, do I need to create two MediaPlayer copies? - Turalllb
    • one
      Well, see: if you load a resource, then the context is needed for just to load the resource by its id. If you look at the source code of the MediaPlayer class, then right away there is the context.getResources().openRawResourceFd(resid) , and if I remember correctly, getResources() will return null if you call it before the component (whether it activates or the service) initialized (i.e. before onCreate ). Why exactly? Well, the platform works, you need to play by its rules. (continued in the next comment) - Agrgg
    • one
      If you want different tracks on different activites, then yes, you need either several media players or one, but reinitialize it with a new source. The first will work faster, but consume more resources, and is hardly suitable if there are really a lot of tracks. There is still such a thing as SoundPool , never used, but it may suit you. In general, it seems to be used for any short sounds (in games, for example), but according to the description it works with a set of audio resources, that is, what you need. - Agrgg