Android AsyncTask对话框快速关闭

时间:2013-11-06 05:08:01

标签: android android-asynctask progressdialog

我的代码:

private class selectBookInAutor extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        arr_book_title.clear();
        arr_book_href.clear();
        mProgressDialog = new ProgressDialog(_context);
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.show();
    }       

    @Override
    protected String doInBackground(String... params) {
        Document doc = null;
        StringBuilder sb = new StringBuilder();
        try {
            doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
            Elements links = doc.select("li>a");
            for (Element link : links) {
                sb.append(link.text());
                arr_book_title.add(link.text());
                arr_book_href.add(Jsoup.clean(link.attr("abs:href"), Whitelist.basic()));
            }

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

        return sb.toString();           
    } 
    @Override
    protected void onPostExecute(String result) {   
        if (result != ""){
            final CharSequence[] items = arr_book_title.toArray(new CharSequence[arr_book_title.size()]);

            final ArrayList seletedItems = new ArrayList();
            AlertDialog.Builder builder = new AlertDialog.Builder(_context);
            builder.setTitle("Select The Difficulty Level");
            builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
                    if (isChecked) {
                        seletedItems.add(indexSelected);
                    }else if(seletedItems.contains(indexSelected)){
                        seletedItems.remove(Integer.valueOf(indexSelected));
                    }
                }
            }).setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    for (Object s : seletedItems){
                        String[] separated = selGroupParam.split(";");
                        String _idautor = separated[0].toString();                          
                        long id_book = db.insertBOOK(_idautor, arr_book_href.get(Integer.valueOf(s.toString())).toString(), "", arr_book_title.get(Integer.valueOf(s.toString())).toString());
                        new **saveBookInAutor().execute(arr_book_href.get(Integer.valueOf(s.toString())).toString(), _idautor, String.valueOf(id_book));**
                    }
                    refreshList();
                }
            }).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                }
            }).create().show();             
        }else{
            Toast.makeText(_context, "Error", Toast.LENGTH_SHORT).show();
        }
        mProgressDialog.dismiss();
    }
}    


private class saveBookInAutor extends AsyncTask<String, Void, String> {
    String _idautor, _idbook;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog2 = new ProgressDialog(_context);
        mProgressDialog2.setMessage("Save to file");
        mProgressDialog2.setIndeterminate(false);
        mProgressDialog2.show();
    }       

    @Override
    protected String doInBackground(String... params) {
        Document doc = null;
        String _html = "";
        _idautor = params[1];
        _idbook = params[2];
        try {
            doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
            _html = doc.select("dd").outerHtml();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Jsoup.clean(_html, Whitelist.basic());           
    } 
    @Override
    protected void onPostExecute(String result) {   
        if (result != ""){
            Toast.makeText(_context, "Save file", Toast.LENGTH_SHORT).show();
            String html = "<html lang='ru'><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/></head><body>"+result+"</body></html>";
            //String html = result;
            **savePageToFile(_idautor + "_" + String.valueOf(_idbook), html);**
        }else{
            Toast.makeText(_context, "Error", Toast.LENGTH_SHORT).show();
        }
        mProgressDialog2.dismiss();
    }
}      


public void refreshList() {
    Intent intent = new Intent(_context, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    _context.startActivity(intent);     
}



public void savePageToFile(String filename, String html) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(_context.openFileOutput(filename, Context.MODE_PRIVATE));
        outputStreamWriter.write(html);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        //Log.e("Exception", "File write failed: " + e.toString());
    } 
}

当您选择页面并单击“确定”时,ProgressDialog将打开mProgressDialog2并显示1秒钟。因此,我没有看到下载页面。

如何使mProgressDialog2一直显示以将页面保存为文件?

谢谢!

UPD

我想要的是:

  1. 启动mProgressDialog。

  2. 下载后页面消失,AlertDialog附带问题选择。

  3. 选择后,只要下载并将文件保存在网页中,就应显示mProgressDialog2。

  4. 然而,mProgressDialog2会在1秒后消失,保存文件的过程会静默进行。

2 个答案:

答案 0 :(得分:0)

在onPostExecute方法中,您无条件地调用

mProgressDialog2.dismiss();

这是在显示后立即关闭对话框。应该将该调用移动到每个按钮的处理程序代码中。 (即正面和负面按钮的onClick方法)

答案 1 :(得分:0)

在onPostExecute()中,比较像

这样的字符串
     if(!result.equals(""))

并尝试一次。

使用equals()方法进行字符串比较。