For循环不完全执行我的异步任务

时间:2013-04-19 03:34:35

标签: java android

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

这是我的for循环

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();
        }



        }

这是我的异步任务

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);
        }

    }

1 个答案:

答案 0 :(得分:0)

异步任务在后台线程上运行,因此您可以直接访问函数doInBackground()中的非线程安全的变量dload_all。也许你可以试试:

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);
    }

}