简体   繁体   English

Java NullPointerException获取资源

[英]Java NullPointerException Getting Resources

I am writing a simple Android application (which is mainly for me to test whatever I may need to use in a real app) and I need to use a MediaPlayer to play a sound. 我正在编写一个简单的Android应用程序(主要是为了测试我在实际应用程序中可能需要使用的应用程序),并且需要使用MediaPlayer播放声音。 In this case, I'm using kalimba.mp3 (no capital letters). 在这种情况下,我使用的是kalimba.mp3 (无大写字母)。 But when I try to run the app, it instantly crashes because of a null object reference. 但是,当我尝试运行该应用程序时,由于空对象引用,它立即崩溃。 The error is below, as is my code. 错误如下,我的代码也一样。 The problem is, I don't see a problem with anything, and it gives me no errors while editing my code. 问题是,我什么都看不到,在编辑代码时没有任何错误。 How do I stop this from throwing an error? 如何停止抛出错误? I've never used a MediaPlayer before. 我以前从未使用过MediaPlayer。 Thanks in advance! 提前致谢!

Code: 码:

// Player of "kalimba.mp3"
private MediaPlayer kalimbaPlayer = MediaPlayer.create(this, R.raw.kalimba);

// Play/stop the sound    
public void playSound(View view) { kalimbaPlayer.start(); }
public void stopSound(View view) { kalimbaPlayer.stop(); kalimbaPlayer.release(); }

Error: 错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference

this is presumably your Activity. this大概是您的活动。 At the time the fields are initialised, the Activity probably isn't fully ready. 在初始化字段时,活动可能尚未完全准备好。

Instead, initialise the MediaPlayer inside the onCreate() method of the Activity. 而是在Activity的onCreate()方法内部初始化MediaPlayer。

create Global variable in your class 在您的班级中创建全局变量

 public Resources mRes;

After this 在这之后

 @Override
Oncreate(Bundle saveInstance){
mRes = getActivity().getResources();
}

Now user mRes object to get resource.... For example 现在,用户mRes对象可以获取资源。

mRes.getString(R.string.SEARCH);

you used onCreate 您使用过onCreate

kalimbaPlayer = MediaPlayer.create(nameActivity.this, R.raw.kalimba); kalimbaPlayer = MediaPlayer.create(nameActivity.this,R.raw.kalimba);

pm . 下午 nameActivity = nameActivity class nameActivity = nameActivity类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM