For循环不能完全做我的异步任务 [英] For loop does not doing my async task completely

查看:109
本文介绍了For循环不能完全做我的异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Im做下载的所有文件。我所做的就是循环,不幸的是我的for循环没有完成我的任务异步它继续这样做,无论是否完成它被下载的第一个文件中的所有循环。请帮助。

下面是我的循环

 的for(int i = 0; I< id.length;我++){
            元素e =(元)nodes.item(I)
            ID [i] =+ CategoriesXMLfunctions.getValue(即,ID);
            名称由[i] =+ CategoriesXMLfunctions.getValue(即,名);
            图片[I] =+ CategoriesXMLfunctions.getValue(即图像);
            simage [I] =+ CategoriesXMLfunctions.getValue(即simage);
            下载[I] =+ CategoriesXMLfunctions.getValue(即,下载);
            笔者[I] =+ CategoriesXMLfunctions.getValue(即,作者);
            体裁[I] =+ CategoriesXMLfunctions.getValue(即,流派);
            大小由[i] =+ CategoriesXMLfunctions.getValue(即大小);
            价格由[i] =+ CategoriesXMLfunctions.getValue(即价格);
            mylist.add(地图);
        id_all = ID [I]
        image_all =图像[I]
        dload_all =下载[I]
        size_all =尺寸[I]
        name_all =名称[I]
        串响应=无效;
        字符串resstring = NULL;
        ArrayList的<&的NameValuePair GT; postParameters =新的ArrayList<&的NameValuePair GT;();
        postParameters.add(新BasicNameValuePair(DEVID,DEVID));
        字符串DEVID = NULL;        尝试{
                DEVID = URLEn coder.en code(Global.getMac(),UTF-8);
            }赶上(UnsupportedEncodingException E1){
                // TODO自动生成catch块
                e1.printStackTrace();
            }
        尝试{
            字符串nURL =HTTP://....url
            响应= CustomHttpClient.executeHttpPost(nURL,postParameters);
            resstring = response.toString();
            字符串信用= resstring;
            字符串priiice价格= [I]
            浮动货币= Float.parseFloat(信贷);
            浮PRI = Float.parseFloat(priiice);            如果(PRI>钱){
               最后AlertDialog.Builder警报=新AlertDialog.Builder(MainStore.this);
                alert.setMessage(学分不够的。);
                alert.setPositiveButton(OK,新DialogInterface.OnClickListener(){
                    公共无效的onClick(DialogInterface对话,诠释whichButton){
                        dialog.cancel();
                    }                });                alert.show();
            }其他{                文件SD = GETDIR(XML,MODE_PRIVATE);                  文件todel =新的文件(SD,ID [I] +XML);
                    todel.delete();
                   字符串filecreat =/\"+id[i]+\".xml;
                   文件newfil =新的文件(SD + filecreat);
                       如果(newfil.exists()){
                        todel.delete();
                       }
                   尝试{
                   如果(!newfil.exists()){
                    newfil.createNewFile();
                }}赶上(IOException异常E1){                   }                尝试{
                     FileWriter的fileWritter =新的FileWriter(newfil);
                                BufferedWriter将bufferWritter =新的BufferedWriter(fileWritter);
                                bufferWritter.write(&所述;的xml>中);
                                bufferWritter.write(<图书>);
                                bufferWritter.write(<&ID GT;+ ID [I] +< / ID>中);
                                bufferWritter.write(<名称>+名[I] +< /名称>);
                                bufferWritter.write(<下载和GT;+下载[I] +< /下载>);
                                bufferWritter.write(<尺寸和GT;+大小[I] +< /尺寸与GT;);
                                bufferWritter.write(<作者>中+作者[I] +< /笔者>);
                                bufferWritter.write(<&流派GT;+流派[I] +< /流派>);
                                bufferWritter.write(<新> 0℃; /新>);
                                bufferWritter.write(< /图书>);
                                bufferWritter.write(&下; / xml的>中);
                                bufferWritter.close();                                Toast.makeText(getApplicationContext(),下载...,Toast.LENGTH_LONG).show();
                        }赶上(IOException异常E1){
                            e1.printStackTrace();
                            Toast.makeText(getApplicationContext(),错误wrting XML+ e1.toString(),Toast.LENGTH_LONG).show();                        }                        downloadallStarted();
                        downloadallfiles();
                        // checkdownloadall();
                        // downloadallFinished();
            }
        }赶上(例外E1){
             Toast.makeText(getApplicationContext(),错误downloadall:+ e1.toString(),Toast.LENGTH_LONG).show();
        }        }

这是我的任务异步

 私人无效startDownloadall(){
         字符串fileURL = dload_all;
         fileURL = fileURL.replace(,%20);
        新DownloadFileAsync1()执行(fileURL);
        Toast.makeText(getApplicationContext(),下载...启动所有,Toast.LENGTH_LONG).show();
    }
类DownloadFileAsync1扩展的AsyncTask<字符串,字符串,字符串> {        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            //的ShowDialog(DIALOG_DOWNLOAD_PROGRESS);
        }        @覆盖
        保护字符串doInBackground(字符串... aurl){            尝试{
                字符串fileURL = dload_all;
                fileURL = fileURL.replace(,%20);
                URL U =新的URL(fileURL);
                HttpURLConnection的C =(HttpURLConnection类)u.openConnection();
                c.setRequestMethod(GET);
                c.setDoOutput(真);
                c.connect();                字符串PATH = GETDIR(电子书,MODE_PRIVATE)的ToString();
                串ebookfile =;
                //字符串文件名= ID [指数]
                字符串文件名= id_all;
                如果(fileURL.endsWith(PDF))
                  ebookfile =文件名+PDF格式。                其他
                  ebookfile =文件名+。EPUB
                bookfile = ebookfile;
                Global.setBookfile(bookfile);
                档案文件=新的文件(路径);
                file.mkdirs();
                文件OUTPUTFILE =新的文件(文件,ebookfile);
                FOS的FileOutputStream =新的FileOutputStream(OUTPUTFILE);                lenghtOfFilee = c.getContentLength();
                在的InputStream = c.getInputStream();
                字节[]缓冲区=新的字节[1024];
                INT LEN1 = 0;
                总长= 0;                而((LEN1 = in.read(缓冲液))大于0){
                    总+ = LEN1; //总=总LEN1 +
                    // publishProgress(+(int)的((总* 100)/ lenghtOfFilee));
                    fos.write(缓冲液,0,LEN1);
                }
                fos.close();
            }赶上(例外五){
               // Log.d(下载,e.getMessage());
            }            返回null;        }        保护无效onProgressUpdate(字符串...进度){
            // Log.d(ANDRO_ASYNC进步[0]);
             //mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }        @覆盖
        保护无效onPostExecute(字符串使用){
            Global.setBookfile(bookfile);
            Toast.makeText(getApplicationContext(),下载...+ lenghtOfFilee,Toast.LENGTH_LONG).show();
            checkdownloadall();
            // dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        }    }


解决方案

这是异步任务在后台线程)中运行,所以你直接访问功能doInBackground(可变dload_all这不是线程安全的。也许你可以试试:

 私人无效startDownloadall(){
     //字符串fileURL = dload_all;
     // fileURL = fileURL.replace(,%20);
    新DownloadFileAsync1()执行(dload_all,id_all)。
    Toast.makeText(getApplicationContext(),下载...启动所有,Toast.LENGTH_LONG).show();
}
类DownloadFileAsync1扩展的AsyncTask<字符串,字符串,字符串> {    @覆盖
    在preExecute保护无效(){
        super.on preExecute();
        //的ShowDialog(DIALOG_DOWNLOAD_PROGRESS);
    }    @覆盖
    保护字符串doInBackground(字符串... aurl){        尝试{
            串fileURL = ARGS [0];
            fileURL = fileURL.replace(,%20);
            URL U =新的URL(fileURL);
            HttpURLConnection的C =(HttpURLConnection类)u.openConnection();
            c.setRequestMethod(GET);
            c.setDoOutput(真);
            c.connect();            字符串PATH = GETDIR(电子书,MODE_PRIVATE)的ToString();
            串ebookfile =;
            //字符串文件名= ID [指数]
            字符串文件名= ARGS [1];
            如果(fileURL.endsWith(PDF))
              ebookfile =文件名+PDF格式。            其他
              ebookfile =文件名+。EPUB
            bookfile = ebookfile;
            Global.setBookfile(bookfile);
            档案文件=新的文件(路径);
            file.mkdirs();
            文件OUTPUTFILE =新的文件(文件,ebookfile);
            FOS的FileOutputStream =新的FileOutputStream(OUTPUTFILE);            lenghtOfFilee = c.getContentLength();
            在的InputStream = c.getInputStream();
            字节[]缓冲区=新的字节[1024];
            INT LEN1 = 0;
            总长= 0;            而((LEN1 = in.read(缓冲液))大于0){
                总+ = LEN1; //总=总LEN1 +
                // publishProgress(+(int)的((总* 100)/ lenghtOfFilee));
                fos.write(缓冲液,0,LEN1);
            }
            fos.close();
        }赶上(例外五){
           // Log.d(下载,e.getMessage());
        }        返回null;    }    保护无效onProgressUpdate(字符串...进度){
        // Log.d(ANDRO_ASYNC进步[0]);
         //mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }    @覆盖
    保护无效onPostExecute(字符串使用){
        Global.setBookfile(bookfile);
        Toast.makeText(getApplicationContext(),下载...+ lenghtOfFilee,Toast.LENGTH_LONG).show();
        checkdownloadall();
        // dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }}

Im doing Download All of files. What I did was for loop, unfortunately my for loop does not finish my async task it continues doing all the loop regardless if it finished the first file that was downloading. Help please.

Here is my for loop

for (int i = 0; i < id.length; i++) {
            Element e = (Element)nodes.item(i);
            id[i] = ""+CategoriesXMLfunctions.getValue(e, "id");
            name[i] = ""+CategoriesXMLfunctions.getValue(e, "name");
            image[i] = ""+CategoriesXMLfunctions.getValue(e, "image");
            simage[i] = ""+CategoriesXMLfunctions.getValue(e, "simage");
            download[i] = ""+CategoriesXMLfunctions.getValue(e, "download");
            author[i] = ""+CategoriesXMLfunctions.getValue(e, "author");
            genre[i] = ""+CategoriesXMLfunctions.getValue(e, "genre");
            size[i] = ""+CategoriesXMLfunctions.getValue(e, "size");
            price[i] = ""+CategoriesXMLfunctions.getValue(e, "price");
            mylist.add(map);    


        id_all = id[i];
        image_all = image[i];
        dload_all = download[i];
        size_all = size[i];
        name_all = name[i];
        String response = null;
        String resstring = null;
        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("devid", "devid"));
        String devid=null;

        try {
                devid =  URLEncoder.encode(Global.getMac(), "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        try {
            String nURL = "http://....url";
            response = CustomHttpClient.executeHttpPost(nURL, postParameters);
            resstring=response.toString();


            String credit = resstring;
            String priiice = price[i];


            float money = Float.parseFloat(credit);
            float pri = Float.parseFloat(priiice);

            if(pri>money){
               final AlertDialog.Builder alert = new AlertDialog.Builder(MainStore.this);
                alert.setMessage("Credits not enough.");
                alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }

                });

                alert.show();
            }else{

                File sd = getDir("xml",MODE_PRIVATE);

                  File todel = new File(sd,id[i]+".xml");
                    todel.delete();
                   String filecreat= "/"+id[i]+".xml";
                   File newfil = new File(sd+ filecreat);
                       if(newfil.exists()){
                        todel.delete();
                       }
                   try{
                   if(!newfil.exists()){
                    newfil.createNewFile();
                }}catch(IOException e1){

                   }



                try{
                     FileWriter fileWritter = new FileWriter(newfil);
                                BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
                                bufferWritter.write("<xml>");
                                bufferWritter.write("<books>");
                                bufferWritter.write("<id>"+id[i]+"</id>");
                                bufferWritter.write("<name>"+name[i]+"</name>");
                                bufferWritter.write("<download>"+download[i]+"</download>");
                                bufferWritter.write("<size>"+size[i]+"</size>");
                                bufferWritter.write("<author>"+author[i]+"</author>");
                                bufferWritter.write("<genre>"+genre[i]+"</genre>");
                                bufferWritter.write("<new>0</new>");
                                bufferWritter.write("</books>");
                                bufferWritter.write("</xml>");
                                bufferWritter.close();

                                Toast.makeText(getApplicationContext(), "Downloading...", Toast.LENGTH_LONG).show();    
                        }catch(IOException e1){
                            e1.printStackTrace();
                            Toast.makeText(getApplicationContext(), "error wrting xml "+e1.toString(), Toast.LENGTH_LONG).show();  

                        }   

                        downloadallStarted();
                        downloadallfiles();
                        //checkdownloadall();
                        //downloadallFinished();
            }


        }catch (Exception e1){
             Toast.makeText(getApplicationContext(), "Error in downloadall: " +e1.toString(), Toast.LENGTH_LONG).show();
        }



        }

And here is my async task

private void startDownloadall() {
         String fileURL = dload_all;
         fileURL = fileURL.replace(" ", "%20");
        new DownloadFileAsync1().execute(fileURL);
        Toast.makeText(getApplicationContext(), "Downloading...start all", Toast.LENGTH_LONG).show();
    }
class DownloadFileAsync1 extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }

        @Override
        protected String doInBackground(String... aurl) {

            try {
                String fileURL = dload_all;
                fileURL = fileURL.replace(" ", "%20");
                URL u = new URL(fileURL);
                HttpURLConnection c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();

                String PATH = getDir("ebook", MODE_PRIVATE).toString();
                String ebookfile = "";
                //String filename = id[index];
                String filename = id_all;
                if(fileURL.endsWith("pdf"))
                  ebookfile = filename+".pdf";

                else
                  ebookfile = filename+".epub";  
                bookfile = ebookfile;
                Global.setBookfile(bookfile);
                File file = new File(PATH);
                file.mkdirs();
                File outputFile = new File(file, ebookfile);
                FileOutputStream fos = new FileOutputStream(outputFile);

                lenghtOfFilee = c.getContentLength();


                InputStream in = c.getInputStream();
                byte[] buffer = new byte[1024];
                int len1 = 0;
                long total = 0;

                while ((len1 = in.read(buffer)) > 0) {
                    total += len1; //total = total + len1
                    //publishProgress("" + (int)((total*100)/lenghtOfFilee));
                    fos.write(buffer, 0, len1);
                }
                fos.close();
            } catch (Exception e) {
               // Log.d("Downloader", e.getMessage());
            }

            return null;

        }

        protected void onProgressUpdate(String... progress) {
            // Log.d("ANDRO_ASYNC",progress[0]);
             //mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String unused) {
            Global.setBookfile(bookfile);
            Toast.makeText(getApplicationContext(), "Downloading..."+lenghtOfFilee, Toast.LENGTH_LONG).show();
            checkdownloadall();
            //dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        }

    }

解决方案

An asynchronous task runs on a background thread, so you directly access variable dload_all in function doInBackground() that is not thread safe. Maybe you can try:

private void startDownloadall() {
     //String fileURL = dload_all;
     //fileURL = fileURL.replace(" ", "%20");
    new DownloadFileAsync1().execute(dload_all, id_all);
    Toast.makeText(getApplicationContext(), "Downloading...start all", Toast.LENGTH_LONG).show();
}
class DownloadFileAsync1 extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... aurl) {

        try {
            String fileURL = args[0];
            fileURL = fileURL.replace(" ", "%20");
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH = getDir("ebook", MODE_PRIVATE).toString();
            String ebookfile = "";
            //String filename = id[index];
            String filename = args[1];
            if(fileURL.endsWith("pdf"))
              ebookfile = filename+".pdf";

            else
              ebookfile = filename+".epub";  
            bookfile = ebookfile;
            Global.setBookfile(bookfile);
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, ebookfile);
            FileOutputStream fos = new FileOutputStream(outputFile);

            lenghtOfFilee = c.getContentLength();


            InputStream in = c.getInputStream();
            byte[] buffer = new byte[1024];
            int len1 = 0;
            long total = 0;

            while ((len1 = in.read(buffer)) > 0) {
                total += len1; //total = total + len1
                //publishProgress("" + (int)((total*100)/lenghtOfFilee));
                fos.write(buffer, 0, len1);
            }
            fos.close();
        } catch (Exception e) {
           // Log.d("Downloader", e.getMessage());
        }

        return null;

    }

    protected void onProgressUpdate(String... progress) {
        // Log.d("ANDRO_ASYNC",progress[0]);
         //mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        Global.setBookfile(bookfile);
        Toast.makeText(getApplicationContext(), "Downloading..."+lenghtOfFilee, Toast.LENGTH_LONG).show();
        checkdownloadall();
        //dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

}

这篇关于For循环不能完全做我的异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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