[英]Android mediaplayer using uri causes app crash
I have been working to resolve this problem for the last three days and cannot get it working. 我过去三天一直在努力解决此问题,但无法正常工作。 These are the steps of my app:
这些是我的应用程序的步骤:
FATAL EXCEPTION: main 致命异常:主要
Process: com.arcitech.developer.ultimatesoundboard, PID: 22967
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.arcitech.developer.ultimatesoundboard.activities.ItemDetailFragment$4.onClick(ItemDetailFragment.java:153)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
the filepath(uri) I am saving to the database is: Content://com.android.providers.media.documents/document/audio%3A15790 我要保存到数据库的文件路径(uri)是:Content://com.android.providers.media.documents/document/audio%3A15790
and the code I am using is located in the onCreateView of a fragment: 我正在使用的代码位于片段的onCreateView中:
MediaPlayer m;
playSound.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (m != null) {
m.stop();
m.release();
m = null;
}
m = MediaPlayer.create(getActivity(), Uri.parse(mItem.filePath));
m.start();
m.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer m) {
countdownTimerHandler.removeCallbacks(countdownTimerRunnable);
}
});
}
});
According to the doc for MediaPlayer.create() , it can return null if for some reason MediaPlayer cannot be created. 根据MediaPlayer.create()的文档,如果由于某种原因无法创建MediaPlayer,则它可以返回null。 You should be checking the return value for null every time unless you are very confident that it will not return null (but even then, do it for safety).
您应该每次都检查返回值是否为空,除非您非常有信心它不会返回空值(但即使那样,为了安全起见也要这样做)。
You may also want to check the log at the time create() is called to see if Android is leaving any clues as to why creation failed. 您可能还想在调用create()时检查日志,以查看Android是否留下任何有关创建失败原因的线索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.