为什么我不能在 AppCompatActivity 的函数外部使用 create 方法?

huangapple go评论70阅读模式
英文:

why I can not use create method out side a function in AppCompatActivity

问题

以下是翻译好的内容:

当我像这样编写代码时,我的应用在启动时崩溃:

public class MainActivity extends AppCompatActivity {
    MediaPlayer mplayer= MediaPlayer.create(this,R.raw.song);
    public void playMusic(View view){
        mplayer.start();
    }
    public void pauseMusic(View view){
        mplayer.pause();
    }

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


    }
}

但是当我像这样编写上面的代码时,它完美地工作:

public class MainActivity extends AppCompatActivity {
    MediaPlayer mplayer;
    public void playMusic(View view){
        mplayer= MediaPlayer.create(this,R.raw.song);
        mplayer.start();
    }
    public void pauseMusic(View view){
        mplayer.pause();
    }

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


    }
}

请问有人能告诉我第一个代码有什么问题吗?

谢谢

英文:

My app is crashing when I launch when I write code like this

public class MainActivity extends AppCompatActivity {
    MediaPlayer mplayer= MediaPlayer.create(this,R.raw.song);
    public void playMusic(View view){
        mplayer.start();
    }
    public void pauseMusic(View view){
        mplayer.pause();
    }

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


    }
}

but when I write above code like this then it's working perfectly fine

public class MainActivity extends AppCompatActivity {
    MediaPlayer mplayer;
    public void playMusic(View view){
        mplayer= MediaPlayer.create(this,R.raw.song);
        mplayer.start();
    }
    public void pauseMusic(View view){
        mplayer.pause();
    }

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


    }
}

please anybody tell me what is wrong with first code

Thanks

答案1

得分: 0

因为玩家必须在上下文不为空的情况下进行初始化。也就是说,在上面的代码中,player 中的 context == null。因此,应用程序崩溃。

英文:

because the player must be initialized at the moment when the context is not empty. That is, in the upper code, context == null in player. Therefore, the application crashes.

huangapple
  • 本文由 发表于 2020年4月8日 18:18:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/61098332.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定