英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论