【问题标题】:Updating progress on progress dialog from AsyncTask can't build无法从 AsyncTask 更新进度对话框的进度
【发布时间】:2013-07-24 10:09:27
【问题描述】:

我无法构建我的项目,因为 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"
    }
}

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

【问题讨论】:

  • 请注意:您永远不能从第二个线程修改 UI - 您只能从主线程(UI 线程)进行修改。第二个线程必须告诉主线程要在 UI 中更改什么。

标签: android eclipse android-asynctask download


【解决方案1】:
 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]);
    }
}

【讨论】:

  • 谢谢,我忘了在使用它的外部函数中声明 ProgressDialog 在 AsyncTask 中
【解决方案2】:

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

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

干杯!

【讨论】:

    【解决方案3】:

    “此代码适用于从网络下载数据”

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

    【讨论】:

      猜你喜欢
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多