我正在尝试在我当前的 Android 项目中实现 DownloadManager 从 URL 下载 mp3。我使用的 Android SDK 版本是 2.3.3。甚至通过单击按钮开始下载。从那里将一个字符串传递给 downloadPodcast 方法以开始下载。我遇到的问题是尝试开始下载时出现空指针异常。我已经通过调试器并验证了 URL 字符串已正确传递给此方法并包含有效的字符串值。失败的特定行是:
downloadId= dm.enqueue(new DownloadManager.Request(Uri.parse(podcastUrl))
调试后,我相信我已将其范围缩小到“dm”。即使在我相信是在 onCreate 方法中正确初始化它之后,此项的值也始终为“null”。我已经查看了几个示例,并相信我正在正确地实现这一点,我只是在死胡同,不知道为什么这仍然是空的。
主要活动代码:
public class Podcasts extends ListActivity{
private DownloadManager dm;
private long downloadId=-1L;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.podcasts);
dm = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
下载方式:
public void downloadPodcast (String podcastUrl){
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir();
downloadId= dm.enqueue(new DownloadManager.Request(Uri.parse(podcastUrl))
.setAllowedOverRoaming(false)
.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "test.mp3")
.setTitle("TEST"));
}
添加了 Logcat:
FATAL EXCEPTION: main
java.lang.NullPointerException
at tv.undignified.android.Podcasts.downloadPodcast(Podcasts.java:275)
at tv.undignified.android.Podcasts$CustomAdapter$2.onClick(Podcasts.java:218)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9080)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)