Android异步任务下载失败错误
我开发了一个应用程序,从互联网上获取内容,并相应地在设备屏幕上显示。程序运行得很好,有点慢。加载和显示内容大约需要3-4秒。我想把完成所有工作(抓取web内容并显示)的代码放在后台线程中。另外,我想显示一个进度对话框Android异步任务下载失败错误,android,asynchronous,download,android-asynctask,task,Android,Asynchronous,Download,Android Asynctask,Task,我开发了一个应用程序,从互联网上获取内容,并相应地在设备屏幕上显示。程序运行得很好,有点慢。加载和显示内容大约需要3-4秒。我想把完成所有工作(抓取web内容并显示)的代码放在后台线程中。另外,我想显示一个进度对话框 public class Activity1 extends Activity { private ProgressDialog progressDialog; @Override public void onCreate(Bundle savedInst
public class Activity1 extends Activity
{
private ProgressDialog progressDialog;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncTask<Integer, Integer, Boolean>()
{
ProgressDialog progressDialog;
@Override
protected void onPreExecute()
{
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(Activity1.this, "",
"Loading...");
}
@Override
protected Boolean doInBackground(Integer... params)
{
if (params == null)
{
return false;
}
try
{
/*
* This is run on a background thread, so we can sleep here
* or do whatever we want without blocking UI thread. A more
* advanced use would download chunks of fixed size and call
* publishProgress();
*/
Thread.sleep(params[0]);
// HERE I'VE PUT ALL THE FUNCTIONS THAT WORK FOR ME
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
/*
* The task failed
*/
return false;
}
/*
* The task succeeded
*/
return true;
}
@Override
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
/*
* Update here your view objects with content from download. It
* is save to dismiss dialogs, update views, etc., since we are
* working on UI thread.
*/
AlertDialog.Builder b = new AlertDialog.Builder(Activity1.this);
b.setTitle(android.R.string.dialog_alert_title);
if (result)
{
b.setMessage("Download succeeded");
}
else
{
b.setMessage("Download failed");
}
b.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int arg1)
{
dlg.dismiss();
}
});
b.create().show();
}
}.execute(2000);
/* new Thread()
{
@Override
public void run()
{
// dismiss the progressdialog
progressDialog.dismiss();
}
}.start();
}*/
}
公共类活动1扩展活动
{
私有进程对话;
@凌驾
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
新建异步任务()
{
进行对话进行对话;
@凌驾
受保护的void onPreExecute()
{
/*
*这是在doInBackground()之前的UI线程上执行的。它是
*显示进度对话框的最佳位置。
*/
progressDialog=progressDialog.show(Activity1.this,“,
“装载…”);
}
@凌驾
受保护的布尔doInBackground(整数…参数)
{
if(params==null)
{
返回false;
}
尝试
{
/*
*这是在后台线程上运行的,所以我们可以在这里睡觉
*或者在不阻塞UI线程的情况下做任何我们想做的事情
*高级使用将下载固定大小的块并调用
*出版进度();
*/
Thread.sleep(参数[0]);
//在这里,我已经把所有的功能,为我工作
}
捕获(例外e)
{
Log.e(“tag”,e.getMessage());
/*
*任务失败了
*/
返回false;
}
/*
*任务成功了
*/
返回true;
}
@凌驾
受保护的void onPostExecute(布尔结果)
{
progressDialog.disclose();
/*
*在此处使用下载的内容更新您的视图对象
*保存以关闭对话框、更新视图等,因为
*在UI线程上工作。
*/
AlertDialog.Builder b=新建AlertDialog.Builder(Activity1.this);
b、 setTitle(android.R.string.dialog\u alert\u title);
如果(结果)
{
b、 setMessage(“下载成功”);
}
其他的
{
b、 setMessage(“下载失败”);
}
b、 setPositiveButton(getString(android.R.string.ok),
新建DialogInterface.OnClickListener()
{
@凌驾
公共void onClick(对话框接口dlg,int arg1)
{
dlg.discouse();
}
});
b、 create().show();
}
}.执行(2000年);
/*新线程()
{
@凌驾
公开募捐
{
//关闭progressdialog
progressDialog.disclose();
}
}.start();
}*/
}
如果使用此代码运行应用程序,则会得到以下结果:。另一方面,如果我保留最后一个线程,应用程序就会崩溃,NullPointerException。我真的不知道该怎么办了
如果您能给我一个替代此代码的选项,而不仅仅是一些提示,我将非常感激,因为我是android新手,我真的不知道很多。谢谢。
更新:
我不想显示下载进度,我想显示进度对话框,直到应用程序准备好显示全部内容。最好的方法是使用AsyncTask类,因为它允许您执行一些后台进程,同时更新UI(在您的情况下,它是一个进度条) 这是一个示例代码:
ProgressDialog mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("the url to the file you want to download");
异步任务将如下所示:
private class DownloadFile extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... url) {
int count;
try {
URL url = new URL(url[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/somewhere/nameofthefile.ext");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
}
如果要在文件完全下载后执行某些代码,还需要重写onPostExecute方法。最好的方法是使用AsyncTask类,因为它允许您执行一些后台进程,同时更新UI(在您的情况下,它是一个进度条) 这是一个示例代码:
ProgressDialog mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("the url to the file you want to download");
异步任务将如下所示:
private class DownloadFile extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... url) {
int count;
try {
URL url = new URL(url[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/somewhere/nameofthefile.ext");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
}
如果要在文件完全下载后执行某些代码,还需要重写onPostExecute方法。您应该为AsyncTask创建一个内部类,如下所示:
private class YourTask extends AsyncTask<Context, Void, Void>
{
ProgressDialog dialog = new ProgressDialog(mContext);
protected void onPreExecute()
{
dialog.setMessage("loading..");
dialog.show();
}
protected Void doInBackground(Context... params)
{
// ...
return null;
}
protected void onPostExecute(final Void unused)
{
dialog.dismiss();
}
}
有关更多详细信息,请检查一下:
您应该为异步任务创建一个内部类,如下所示:
private class YourTask extends AsyncTask<Context, Void, Void>
{
ProgressDialog dialog = new ProgressDialog(mContext);
protected void onPreExecute()
{
dialog.setMessage("loading..");
dialog.show();
}
protected Void doInBackground(Context... params)
{
// ...
return null;
}
protected void onPostExecute(final Void unused)
{
dialog.dismiss();
}
}
有关更多详细信息,请检查一下:
当您使用新线程时,您的应用程序会崩溃,因为进度对话框没有在那里初始化 在新线程中使用:
`progressDialog = ProgressDialog.show(Activity1.this, "","Loading...");
关于警报对话框:基本上要么params为null,要么逻辑抛出一些异常。这不是真的
因此,请检查ddms日志并将其发布到此处
`当您使用新线程时,您的应用程序会崩溃,因为进度对话框没有在那里初始化 在新线程中使用:
`progressDialog = ProgressDialog.show(Activity1.this, "","Loading...");
关于警报对话框:基本上要么params为null,要么逻辑抛出一些异常。这不是真的
因此,请检查ddms日志并将其发布到此处
`访问此网站,这里有n