onCreate 之外的 MediaPlayer 定义抛出 NullpointerException?

MediaPlayer definition outside onCreate throws NullpointerException?

我需要我的 MediaPlayer 对象作为 class 变量而不是本地 oncreate 可见。

但是当我尝试像这样启动它时-

public class TextAct extends AppCompatActivity
{

    MediaPlayer wavesMp =  MediaPlayer.create(this, R.raw.river);//Line 132
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
    .
    .
    }

这也失败并出现同样的错误-

public class TextAct extends AppCompatActivity
{

    MediaPlayer wavesMp; //Line 132
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
     wavesMp=  MediaPlayer.create(this, R.raw.river);
    .
    }

Logcat 说-

Process: com.app24.gg.relaaax, PID: 24202 java.lang.RuntimeException: Unable to instantiate activity > ComponentInfo{com.app24.gg.relaaax/com.app24.gg.relaaax.TextAct}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2126) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2249) at android.app.ActivityThread.access0(ActivityThread.java:141) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1212) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5113) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at android.content.ContextWrapper.getResources(ContextWrapper.java:89) at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:78) at android.media.MediaPlayer.create(MediaPlayer.java:844) at com.app24.gg.relaaax.TextAct.(TextAct.java:132)

MediaPlayer 需要上下文。而如果onCreate方法没有被调用,那么Activity就没有准备好,它的Context就不能使用了。