用AsyncTask下载图像 [英] Download images with AsyncTask

查看:172
本文介绍了用AsyncTask下载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太确定我的代码或结构出了什么问题。我想使用AsyncTask下载图像并同时显示进度条。但是我尝试了几种不同的做法。它仍然失败,不知道它有什么问题。我的结构流程是



ContentID是一个字符串数组,用于存储图像的内容ID。



主要问题:它设法从网址下载图像并存储到手机中,但下载的图像是相同的图像。它应该是不同的图像,这不是我的预期。



次要问题:进度条在应用程序下载图像时弹出,但是进度条没有更新进度。它只是保持0%,并在下载完成后被解除。



我想知道是什么原因导致主要和次要问题,我提到。如果您知道我的代码有什么问题,请留下评论或回答。任何帮助将不胜感激。

  if(isSyncSuccess){

SetConstant.IMAGE_EXIST = 1;
pDialog = new ProgressDialog(GalleryScreen.this);
pDialog.setMessage(下载文件,请稍候...);
pDialog.setIndeterminate(false);
pDialog.setProgress(0);
pDialog.setMax(contentId.length);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);


if(contentId.length> 0){
Log.i(TAG,contentid.length:+ contentId.length); (int i = 0; i< contentId.length; i ++){
if(helper.databaseChecking(useremail,contentId [i])){
contentdownload = i;
SetConstant.CONTENT_ID = contentId [i];

String URL = SetConstant.URL_DOWNLOAD_CONTENT + contentId [i];

DownloadFile downloadFile = new DownloadFile();
downloadFile.execute(URL);


}



私有类DownloadFile扩展AsyncTask< String,Integer,String> {
@Override
protected String doInBackground(String ... sUrl){
Bitmap bm;
InputStream in;

尝试{

in = new java.net.URL(sUrl [0])。openStream();
bm = BitmapFactory.decodeStream(new PatchInputStream(in));
文件存储=新文件(Environment.getExternalStorageDirectory()+ File.separator +/ Image /);
Log.i(TAG,storage:+ storage);
Log.i(TAG,storage:+ storage.getAbsolutePath());
if(!storage.exists()){
storage.mkdirs();

}
String FileName =/\"+SetConstant.CONTENT_ID+\".jpg;
FileOutputStream fos = new FileOutputStream(storage + FileName);
bm.compress(Bitmap.CompressFormat.JPEG,85,fos);

String filepath = storage + FileName;
文件filecheck =新建文件(filepath);
long fileSize = filecheck.length();
fos.flush();
fos.close();

Log.i(TAG,bm:+ bm);
Log.i(TAG,fos:+ fos);
Log.i(TAG,filesize:+ fileSize);
Log.i(TAG,filepath:+ filepath);


}
catch(IOException e1){
e1.printStackTrace();
}

返回null;
}

@Override
protected void onPreExecute(){
super.onPreExecute();
pDialog.show();
}

@Override
protected void onProgressUpdate(Integer ... progress){
super.onProgressUpdate(progress);
pDialog.setProgress(progress [0]);
}

protected void onPostExecute(String result){
super.onPostExecute(result);
pDialog.dismiss();
}
}

修改



现在,可以根据进度条下载图像的应用程序也在工作!但是我有另一个问题是如何在应用程序无法完成下载时返回错误消息。目前当应用程序无法下载时会崩溃。我相信我不应该在doInBackground一边运行它。但是我可以在哪里做检查?任何想法如何作为错误消息返回并请求用户重试而不是崩溃的应用程序?

解决方案

您在doInBackGround(...)中从未调用过onProgressUpdate;请注意,运行AsyncTask的多重实例是一个坏主意。这是我建议的:



if(isSyncSuccess){

  SetConstant.IMAGE_EXIST = 1; 
pDialog = new ProgressDialog(GalleryScreen.this);
pDialog.setMessage(下载文件,请稍候...);
pDialog.setIndeterminate(false);
pDialog.setProgress(0);
pDialog.setMax(contentId.length);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);

new DownloadFile()。execute();

}
}

private class DownloadFiles extends AsyncTask< String,Integer,String> {
@Override
protected String doInBackground(String ... sUrl){
Bitmap bm;
InputStream in;
if(contentId.length> 0){

for(int i = 0; i< contentId.length; i ++){
if(helper.databaseChecking(useremail,contentId [i])){
contentdownload = i;
SetConstant.CONTENT_ID = contentId [i];

String URL = SetConstant.URL_DOWNLOAD_CONTENT + contentId [i];
//你在这里的环聊

publishProgress(30);
//进度更新

}
尝试{

in = new java.net.URL(sUrl [0]) .openStream();
bm = BitmapFactory.decodeStream(new PatchInputStream(in));
文件存储=新文件(Environment.getExternalStorageDirectory()+ File.separator +/ Image /);
Log.i(TAG,storage:+ storage);
Log.i(TAG,storage:+ storage.getAbsolutePath());
if(!storage.exists()){
storage.mkdirs();

}
String FileName =/\"+SetConstant.CONTENT_ID+\".jpg;
FileOutputStream fos = new FileOutputStream(storage + FileName);
bm.compress(Bitmap.CompressFormat.JPEG,85,fos);

String filepath = storage + FileName;
文件filecheck =新建文件(filepath);
long fileSize = filecheck.length();
fos.flush();
fos.close();




}
catch(IOException e1){
e1.printStackTrace();
}

返回null;
}

@Override
protected void onPreExecute(){
super.onPreExecute();
pDialog.show();
}

@Override
protected void onProgressUpdate(Integer ... progress){
super.onProgressUpdate(progress);
pDialog.setProgress(progress [0]);
}

protected void onPostExecute(String result){
super.onPostExecute(result);
pDialog.dismiss();
}
}

当然这个代码不运行,你需要修复范围。但是我想提出的是你的循环应该在doInBackGround(...)中,在这种情况下,应该只给定一个AsyncTask实例,并调用onProgressUpdate();


I'm not really sure what goes wrong with my code or structure. I wanted to use AsyncTask to download images and display out the progress bar at the mean time. But I tried out a few different way of doing it. It still failed and no idea what's wrong with it. My structure flow is

ContentID is a string array that stores the content ID of the Images.

Primary Issue: It managed to download images from the url and store into the phone, but the downloaded images are all the same image. It should be different images, it's not what I expected.

Secondary Issue: The progress bar pop up while the application downloading images, but the progress bar did not update it's progress. It just remains 0% and dismissed after the download completed.

I wanted to know what causes primary and secodary issue as i mentioned. Please leave a comment or answer if you might know what's wrong with my code. Any help will be appreciated.

if(isSyncSuccess){

     SetConstant.IMAGE_EXIST = 1;
     pDialog = new ProgressDialog(GalleryScreen.this);
     pDialog.setMessage("Downloading file. Please wait...");
     pDialog.setIndeterminate(false);
     pDialog.setProgress(0);
     pDialog.setMax(contentId.length);
     pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
     pDialog.setCancelable(true);


     if (contentId.length>0){
     Log.i(TAG, "contentid.length:" +contentId.length);
         for (int i=0;i<contentId.length;i++){
             if(helper.databaseChecking(useremail, contentId[i])){
                 contentdownload = i;
                 SetConstant.CONTENT_ID = contentId[i]; 

                 String URL = SetConstant.URL_DOWNLOAD_CONTENT+contentId[i];

                 DownloadFile downloadFile = new DownloadFile();
                 downloadFile.execute(URL);


                 }



    private class DownloadFile extends AsyncTask<String, Integer, String>{
    @Override
    protected String doInBackground(String... sUrl){
                Bitmap bm;
                InputStream in;

        try{

            in = new java.net.URL(sUrl[0]).openStream();
            bm = BitmapFactory.decodeStream(new PatchInputStream(in));
            File storage = new File(Environment.getExternalStorageDirectory() + File.separator + "/Image/");
            Log.i(TAG,"storage:" +storage);
            Log.i(TAG,"storage:" +storage.getAbsolutePath());
            if(!storage.exists()){
                storage.mkdirs();

            }
                String FileName = "/"+SetConstant.CONTENT_ID+".jpg"; 
                FileOutputStream fos = new FileOutputStream(storage + FileName);
                bm.compress(Bitmap.CompressFormat.JPEG, 85, fos);

                String filepath = storage + FileName;
                File filecheck = new File (filepath);
                long fileSize = filecheck.length();
                fos.flush();
                fos.close();

                Log.i(TAG, "bm:" +bm);
                Log.i(TAG, "fos:" +fos);
                Log.i(TAG, "filesize:" +fileSize);
                Log.i(TAG, "filepath:" +filepath);


        }
        catch(IOException e1){
                e1.printStackTrace();
                }   

        return null;
    }

    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        pDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... progress){
        super.onProgressUpdate(progress);
        pDialog.setProgress(progress[0]);
    }

    protected void onPostExecute(String result){
        super.onPostExecute(result);
        pDialog.dismiss();
    }
}

Edit

Now the application able to download images according and the progress bar is working as well! But I got another issue is how to return error message when the application failed to complete the download. Currently when the application failed to download it will crash. I believed that I should not run it inside the doInBackground side. But where else can I do the checking? Any idea how to return as an error message and request for the user to retry instead of crashing the application?

解决方案

You never called onProgressUpdate during your doInBackGround(...); Please note that running multipule instance of AsyncTask is a bad idea. Here is what I suggest:

if (isSyncSuccess) {

    SetConstant.IMAGE_EXIST = 1;
    pDialog = new ProgressDialog(GalleryScreen.this);
    pDialog.setMessage("Downloading file. Please wait...");
    pDialog.setIndeterminate(false);
    pDialog.setProgress(0);
    pDialog.setMax(contentId.length);
    pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    pDialog.setCancelable(true);

    new DownloadFile().execute();

   }
}

private class DownloadFiles extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... sUrl){
                Bitmap bm;
                InputStream in;
                if (contentId.length>0){

             for (int i=0;i<contentId.length;i++){
                 if(helper.databaseChecking(useremail, contentId[i])){
                     contentdownload = i;
                     SetConstant.CONTENT_ID = contentId[i]; 

                     String URL = SetConstant.URL_DOWNLOAD_CONTENT+contentId[i];
                     //YOUR INTRESTING LOOP HERE.

                        publishProgress(30);
                        //SOME INTRESTING NUMBER FOR PROGRESS UPDATE
                     }
             }
    try{

        in = new java.net.URL(sUrl[0]).openStream();
        bm = BitmapFactory.decodeStream(new PatchInputStream(in));
        File storage = new File(Environment.getExternalStorageDirectory() + File.separator + "/Image/");
        Log.i(TAG,"storage:" +storage);
        Log.i(TAG,"storage:" +storage.getAbsolutePath());
        if(!storage.exists()){
            storage.mkdirs();

        }
            String FileName = "/"+SetConstant.CONTENT_ID+".jpg"; 
            FileOutputStream fos = new FileOutputStream(storage + FileName);
            bm.compress(Bitmap.CompressFormat.JPEG, 85, fos);

            String filepath = storage + FileName;
            File filecheck = new File (filepath);
            long fileSize = filecheck.length();
            fos.flush();
            fos.close();




    }
    catch(IOException e1){
            e1.printStackTrace();
            }   

    return null;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog.show();
}

@Override
protected void onProgressUpdate(Integer... progress) {
    super.onProgressUpdate(progress);
    pDialog.setProgress(progress[0]);
}

protected void onPostExecute(String result) {
    super.onPostExecute(result);
    pDialog.dismiss();
}
}

Of course this code don't run and you need to fix the scopes. but what I am trying to suggest is your loop should be in doInBackGround(...), you should only have 1 instance of AsyncTask at given time for this case, and call the onProgressUpdate();

这篇关于用AsyncTask下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆