-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);
    }

}
4

2 回答 2

2

这绝对是一个 NPE,替换

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

this.mpSplash = MediaPlayer.create(this, R.raw.explosion);
于 2012-08-23T04:06:48.900 回答
0

里面onCreate()有线

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

是一个局部变量。

将其替换为

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

*当 NullPointerException 发生时。

onDestroy()

你打过电话了

mpSlash.release()

尚未初始化,但您认为它已初始化onCreate()

于 2012-08-23T04:15:03.617 回答