[英]Error with mediaPlayer.create(this, R.raw.sound) when not in onCreate
[英]Why does MediaPlayer.create throw NullPointer exception when initialised in the beginning of the class but not when initialised in OnCreate method?
在類的開頭使用上下文和資源初始化MediaPlayer對象時,它將引發NullPointer異常,但是在類的開頭聲明它(因此為null),然后在onCreate中以相同的方式對其進行初始化方法,它可以工作。 我在其他對象(例如視圖)上也會發生這種情況,我無法理解為什么以相同的方式初始化它。
public class MainActivity extends AppCompatActivity {
//Commented code is how it is written to run without problems
// private MediaPlayer player;
private MediaPlayer player = MediaPlayer.create(this, R.raw.test); //Throws NullPointer Exception
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// player = MediaPlayer.create(this, R.raw.test);
setContentView(R.layout.activity_main);
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.musicplayer, PID: 17008
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.musicplayer/com.example.android.musicplayer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3066
歡迎使用Stackoverflow。
作為錯誤屬性, create
方法需要上下文。 該上下文僅在活動的onCreate
方法上創建。 就是說,在創建變量時,沒有上下文,原因是尚未發生onCreate
。
進行以下更改:
public class MainActivity extends AppCompatActivity {
//Commented code is how it is written to run without problems
// private MediaPlayer player;
private MediaPlayer player; //Remove the MediaPlayer.create from here
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// player = MediaPlayer.create(this, R.raw.test);
setContentView(R.layout.activity_main);
player = MediaPlayer.create(this, R.raw.test); //and put it here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.