Search code examples
javaandroidandroid-mediaplayerandroid-studio-2.2

MediaPlayer plugin causing the app to crash


When I use MediaPlayer plugin in my code and deploy it on either emulator or Android device, the build finishes without errors but the app crashes on startup on the devices.

Java: MainActivity.java

package com.oniichan.launchpadify;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.media.MediaPlayer;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    final MediaPlayer mp = MediaPlayer.create(this, R.raw.clap1);

    public void clapone(View v){
        Toast.makeText(this, "Playing clap1.wav", Toast.LENGTH_SHORT).show();
        mp.start();
    }
}

XML: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.oniichan.launchpadify.MainActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <Button
            android:layout_width="150px"
            android:layout_height="150px"
            android:layout_margin="10dp"
            android:id="@+id/play1"
            android:onClick="clapone"
            />

    </FrameLayout>
</RelativeLayout>

The problematic line is

final MediaPlayer mp = MediaPlayer.create(this, R.raw.clap1);

If I comment out the above line in the program, everything seems to work fine. Only when I uncomment the above line in an anticipation of something good to happen, the app crashes. Here are screenshots of the app

Application Layout in Android Studio

Application Crash on Emulator

To keep things clean I put the crash log in pastebin lookup here: pastebin.com/NGrqTmAf


Solution

  • This line

    final MediaPlayer mp = MediaPlayer.create(this, R.raw.clap1);

    is executed before the Activity is completely instantiated, so this does not yet exist.

    If you want to have the MediaPlayer as a member variable, leave out the final and do it like this:

    public class MainActivity extends AppCompatActivity {
    
        private MediaPlayer mp;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mp = MediaPlayer.create(this, R.raw.clap1);
        }
    
        // other code here...
    }