异步任务下载如果没有连接抛出空指针异常
问题描述:
先生,我试图处理消息,如果没有互联网连接。但是,如果有任何网络连接,我仍然继续下载时发生空异常错误。首先,它显示网络连接错误的消息,但是当我按下时,会弹出异常错误消息。当我们处理这个案子时我们应该进一步处理什么?异步任务下载如果没有连接抛出空指针异常
timer = new Timer();
boolean isOnline = WebServiceHandler.isOnline(this);
if (isOnline) {
startDownloadTask();
task = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
int progress = downloadProgressBar.getProgress();
notification.contentView.setProgressBar(R.id.pb, downloadProgressBar.getMax(), progress, false);
nm.notify(notificationID, notification);
}
};
timer.schedule(task, 10, 500);
} else {
connectionErrorDialog.show();
onDestroy();
}
}
@Override
public void stopDownloadTask() {
downloadGoodListTask.cancel(true);
downloadGoodListTask.setActivityIsRunning(false);
downloadGoodListTask = null;
}
protected void onDestroy() {
super.onDestroy();
Log.i("Download Activity", "starting to destroy");
//timer.cancel();
wheelProgressBar.destroyDrawingCache();
downloadProgressBar.destroyDrawingCache();
finishDialog.dismiss();
connectionErrorDialog.dismiss();
downloadProgressBar = null;
wheelProgressBar = null;
progressTextView = null;
downloadingTextView = null;
finishDialog = null;
connectionErrorDialog = null;
//timer = null;
nm.cancel(notificationID);
nm = null;
notification = null;
/*downloadTask.cancel(true);
downloadTask.activityIsRunning = false;
downloadTask = null;*/
stopDownloadTask();
timer.cancel();
System.gc();
Log.i("Download Activity", "destroyed");
}
@Override
public void stopDownloadTask() {
downloadGoodListTask.cancel(true);
downloadGoodListTask.setActivityIsRunning(false);
downloadGoodListTask = null;
}
答
不从UI线程外部访问Android UI工具包。使用runOnUIThread方法,将消息发送到Handler或使用AsyncTask。
答
例外是因为downloadGoodListTask为null。要么你应该初始化某个值,要么在stopDownloadTask()中处理异常。
你的意思是通知栏应该在执行后处理? – 2012-07-27 08:58:38
使用onProgressUpdate。看看这里的例子https://eliasbland.wordpress.com/2011/03/11/an-example-of-how-to-run-a-background-task-and-report-progress-in-the-status-使用-的AsyncTask-上的Android吧-/ – 2012-07-27 09:10:48