Java NullPointerException 获取资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25488208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java NullPointerException Getting Resources
提问by Will Eccles
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. In this case, I'm using kalimba.mp3
(no capital letters). 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. Thanks in advance!
我正在编写一个简单的 Android 应用程序(主要是为了测试我在实际应用程序中可能需要使用的任何内容),我需要使用 MediaPlayer 来播放声音。在这种情况下,我使用kalimba.mp3
(无大写字母)。但是当我尝试运行该应用程序时,它会因为空对象引用而立即崩溃。错误如下,我的代码也是。问题是,我没有发现任何问题,并且在编辑我的代码时它没有给我任何错误。我如何阻止它抛出错误?我以前从未使用过 MediaPlayer。提前致谢!
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
采纳答案by ataulm
this
is presumably your Activity. At the time the fields are initialised, the Activity probably isn't fully ready.
this
大概是你的活动。在初始化字段时,Activity 可能还没有完全准备好。
Instead, initialise the MediaPlayer inside the onCreate() method of the Activity.
相反,在 Activity 的 onCreate() 方法中初始化 MediaPlayer。
回答by Pong Petrung
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 类
回答by mahendra
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);
mRes.getString(R.string.SEARCH);