我一直关注网络上的一些Android教程。我尝试尽最大努力复制他的代码,但每当我运行应用程序时它就会崩溃。我查看了控制台,发现它是一个导致它的Nullpointer异常。该应用程序旨在播放声音,然后关闭,然后转到另一个布局。 这是我的代码,请告诉我我做错了什么。
package com.greg.hello;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class MainActivity extends Activity {
MediaPlayer mpSplash;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
MediaPlayer mpSplash = MediaPlayer.create(this, R.raw.explosion);
mpSplash.start();
Thread logoTimer = new Thread(){
public void run(){
try{
int logoTimer=0;
while(logoTimer<8000){
sleep(100);
logoTimer=logoTimer+100;
}
startActivity(new Intent("com.greg.hello.CLEARSCREEN"));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
setContentView(R.layout.tutorial1);
e.printStackTrace();
}
finally{
finish();
}
}
};
logoTimer.start();
finish();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mpSplash.release();
startActivity(new Intent("com.greg.hello.TUTORIALONE"));
setContentView(R.layout.activity_main);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mpSplash.pause();
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mpSplash.start();
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
setContentView(R.layout.activity_main);
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
setContentView(R.layout.activity_main);
}
}
答案 0 :(得分:2)
这绝对是一个NPE,替换
MediaPlayer mpSplash = MediaPlayer.create(this, R.raw.explosion);
与
this.mpSplash = MediaPlayer.create(this, R.raw.explosion);
答案 1 :(得分:0)
内的onCreate()
MediaPlayer mpSplash = MediaPlayer.create(this, R.raw.explosion);
是一个局部变量。
替换为
this.mpSplash = MediaPlayer.create(this, R.raw.explosion);
发生NullPointerException时* 。
onDestroy()
中的
您致电
mpSlash.release()
尚未初始化,但您认为它已在onCreate()