2012-08-23 131 views
-1

我一直在关注网络上的一些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); 
    } 

} 
+2

哪条线路得到NPE初始化? –

+1

如果出现异常,请始终发布堆栈跟踪。 – home

+0

@home和相关的行号。 –

回答

0

onCreate()内部替换

MediaPlayer mpSplash = MediaPlayer.create(this, R.raw.explosion); 

是一个局部变量。

this.mpSplash = MediaPlayer.create(this, R.raw.explosion); 

*更换时发生的NullPointerException。

onDestroy()

你叫

mpSlash.release()

还未被初始化,但你以为它是在onCreate()

+0

非常感谢您的详细解释。 –

2

这绝对一个NPE,与线

MediaPlayer mpSplash = MediaPlayer.create(this, R.raw.explosion); 

this.mpSplash = MediaPlayer.create(this, R.raw.explosion); 
+0

+1看起来像一击。 –