从AsyncTask更新进度对话框的进度无法构建

时间:2013-07-24 10:09:27

标签: android eclipse android-asynctask downloading

我无法构建我的项目,因为eclipse给出了错误

这是开始下载的按钮点击事件

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        ProgressDialog mProgressDialog;
        mProgressDialog = new ProgressDialog(Test.this);
        mProgressDialog.setMessage("Pobieranie");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        DownloadFile downloadFile = new DownloadFile();
        downloadFile.execute("http://google.com");
    }
});

和AsyncTask函数

private class DownloadFile extends AsyncTask<String, Integer, String> {
    [...]
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog.show(); // Here eclipse tell that "mProgressDialog cannot be resolved"
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        mProgressDialog.setProgress(progress[0]); // Here eclipse tell that "mProgressDialog cannot be resolved"
    }
}

那么我应该在哪里插入创建进度对话框的代码?

3 个答案:

答案 0 :(得分:4)

 private class DownloadFile extends AsyncTask<String, Integer, String> {
    ProgressDialog  mProgressDialog;
    String fileName=null;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create ProgressBar
         mProgressDialog = new ProgressDialog(Task.this);
        // Set your ProgressBar Title
        mProgressDialog.setTitle("Downloads");
        mProgressDialog.setIcon(R.drawable.dwnload);
        // Set your ProgressBar Message
        mProgressDialog.setMessage("Updating App Version, Please Wait!");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        // Show ProgressBar
        mProgressDialog.setCancelable(false);
      //  mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.show();
    }

    @Override
    protected String doInBackground(String... sUrl) {
        try {
                    String apkurl = "http://google.com/"+fileName;
                    URL url = new URL(apkurl);
                    HttpURLConnection c = (HttpURLConnection) url
                            .openConnection();
                    c.setRequestMethod("GET");
                    c.setDoOutput(true);
                    c.connect();
                    int fileLength = c.getContentLength();    

                    //File file = new File(PATH);
                    if(file.exists())
                    {
                        file.delete();
                    }
                    file.mkdirs();
                    File outputFile = new File(file, fileName);
        final FileOutputStream fos = new FileOutputStream(outputFile);

                    final InputStream is = c.getInputStream();


            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = is.read(data)) != -1) {
                total += count;
                // Publish the progress
                publishProgress((int) (total * 100 / fileLength));
                fos.write(data, 0, count);
            }

            // Close connection
            fos.flush();
            fos.close();
            is.close();
            }
    }

    catch (Exception e) {
            // Error Log
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
 }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        mProgressDialog.dismiss();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        // Update the ProgressBar
        mProgressDialog.setProgress(progress[0]);
    }
}

答案 1 :(得分:1)

您在OnClickListener的范围内错误地创建了ProgressDialog。

尝试将mProgressDialog的声明移动为Activity / Fragment的私有成员变量,并仅从OnClickListener实例化ProgressDialog。

干杯!

答案 2 :(得分:0)

&#34;此代码适用于从网络下载数据&#34;

 private class Downloadpdf extends AsyncTask<String, Integer,String[]> {
    ProgressDialog progressDialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog=new ProgressDialog(MainActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setMessage("Downloading file...");
        progressDialog.show();

    }

    @Override
    protected  String[] doInBackground(String... strings) {
        String url = strings[0];
        String filename = strings[1];
        String extstoragedir = Environment.getExternalStorageDirectory().toString();
        File folder = new File(extstoragedir, foldername);
        boolean bool = folder.mkdir();

        File file = new File(folder, filename);
        try {
            boolean state = file.createNewFile();
        } catch (IOException e) {
            Log.i("log", e.getLocalizedMessage());
            e.printStackTrace();
        }
        int count;
        try {
            Log.i("log","file downloader called");
            URL contenturl=new URL(url);
            HttpURLConnection httpURLConnection= (HttpURLConnection) contenturl.openConnection();
            httpURLConnection.connect();
            InputStream inputStream=httpURLConnection.getInputStream();
            FileOutputStream outputStream=new FileOutputStream(file);
            int totalsize=httpURLConnection.getContentLength();
            Log.i("log","length of file" +String.valueOf(totalsize));
            byte[] buffer= new byte[MEGABYTE];
            int bufferlength=0;
            while((count=inputStream.read(buffer))>0){
                Log.i("log","length caught");
                bufferlength+=count;
                publishProgress((int) ( (bufferlength / (float)totalsize)*100));
                outputStream.write(buffer,0,count);
            }
            inputStream.close();
            outputStream.flush();
            outputStream.close();


        } catch (MalformedURLException e) {
            Log.i("loge",e.getLocalizedMessage());
            e.printStackTrace();
        } catch (IOException e) {
            Log.i("loge",e.getLocalizedMessage());
            e.printStackTrace();
        }


        String[] data=new String[]{filename,strings[2]};
        return data;


    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        System.out.println(values[0]); //updates progress value

        progressDialog.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(String file[]) {
        progressDialog.dismiss();

    }
}