onCreate外的MediaPlayer定义会抛出NullpointerException吗?

时间:2016-07-01 13:53:09

标签: android android-mediaplayer oncreate

我需要将MediaPlayer对象作为类变量显示,而不是在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说 -

  

处理:com.app24.gg.relaaax,PID:24202   java.lang.RuntimeException:无法实例化活动> ComponentInfo {com.app24.gg.relaaax / com.app24.gg.relaaax.TextAct}:java.lang.NullPointerException   在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2126)   在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2249)   在android.app.ActivityThread.access $ 800(ActivityThread.java:141)   在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1212)   在android.os.Handler.dispatchMessage(Handler.java:102)   在android.os.Looper.loop(Looper.java:136)   在android.app.ActivityThread.main(ActivityThread.java:5113)   at java.lang.reflect.Method.invokeNative(Native Method)   在java.lang.reflect.Method.invoke(Method.java:515)   在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793)   在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)   at dalvik.system.NativeStart.main(Native Method)   引起:java.lang.NullPointerException   在android.content.ContextWrapper.getResources(ContextWrapper.java:89)   在android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:78)   在android.media.MediaPlayer.create(MediaPlayer.java:844)   在com.app24.gg.relaaax.TextAct。(TextAct.java:132)

1 个答案:

答案 0 :(得分:0)

MediaPlayer需要上下文。如果未调用onCreate方法,则表示Activity未准备好,并且无法使用Context