Android 空指针异常

Android 空指针异常,android,Android,我发布了一个免费的应用程序图像滑块,上面有供小孩使用的口语词。几周前,我收到了第一份坠机报告。这种情况似乎很少发生(一周一次) 报告声明:Splash.onCreate()中的NullPointerException 堆栈tace显示以下消息: java.lang.RuntimeException: Unable to start activity java.lang.NullPointerException at android.app.ActivityThread.performL

我发布了一个免费的应用程序图像滑块,上面有供小孩使用的口语词。几周前,我收到了第一份坠机报告。这种情况似乎很少发生(一周一次)

报告声明:Splash.onCreate()中的NullPointerException

堆栈tace显示以下消息:

java.lang.RuntimeException: Unable to start activity 
java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
    at android.app.ActivityThread.access$600(ActivityThread.java:130)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
    at co.uk.musenuovo.michal.Splash.onCreate(Splash.java:18)
    at android.app.Activity.performCreate(Activity.java:5008)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
spash活动中的我的代码(初始屏幕显示图像并播放乐曲5秒):


错误明确指向spash活动中的onstart。这是因为我忘了导入一些库吗?还是我忘了分配什么?我对java非常陌生,不知道如何调试并找出问题所在。我读了很多关于
NullPointerException
的书,但这似乎是一个模糊的错误。谢谢您的帮助。

可能是因为ourSong变量为空。使用前需要检查

ourSong  = MediaPlayer.create(Splash.this, R.raw.xylophone_open);

    if(ourSong  == null) {
        Log.v("LOG", "Create() on MediaPlayer failed.");
    }

您应该始终空检来自捆绑包的数据,包括捆绑包本身。

有一个值明显为空,它可能是未初始化的变量“ourSong”或运行该方法的捆绑包。为bundle添加一行,如System.out.println(ourSong)和/或另一行,并发现哪个变量为null。

看起来像
ourSong
为null

使用简单检查:

if(ourSong != null) {
   ourSong.start();
}

下一次当
ourSong
null
时,它不会
start()
,而是会使你的应用程序崩溃。

因为这是一个运行时错误,你在系统上调试时可能不会出错。 查找导致错误的代码行中的每个句点(.)或左括号([)。其中一个句点/左括号的左边必须有空值。 错误可能是由

ourSong = MediaPlayer.create(Splash.this, R.raw.xylophone_open);
ourSong.start();

我建议您在启动服务之前打印ourSong的值。

Splash.java中的第18行是什么?确切的第18行是什么,co.uk.musenuovo.michal.Splash.onCreate(Splash.java:18)我的赌注是ourSong.start()。如果创建失败,Create可能会返回null,在这种情况下,可能会有一些关于此的日志。第18行似乎是run()语句确保您拥有所有导入。点击Ctrl+shift+O。然后查看是否可以复制错误。这是一个很好的可能性。非常感谢大家的回答。我添加了“日志”这段代码希望你是对的。我在类的顶部添加了import android.util.Log;,并在Eclipse的底部打开了LogCat窗口。我运行应用程序并搜索“在MediaPlayer上创建()失败”消息。在LogCat中找不到任何内容。我希望我做的一切都正确,以确定它是否是我们的SONG变量。奇怪的是,它没有在我的手机或模拟器上崩溃。我不太明白为什么崩溃每周只发生一次。
ourSong = MediaPlayer.create(Splash.this, R.raw.xylophone_open);
ourSong.start();