2011-12-24 84 views
0
Document doc = new Obtainer(context, uri).execute().get(); 

活动类中的此代码呈现了从网址获取xml文档的Obtainer(它扩展了AsyncTask)。这是onPreExecute方法:ProgressDialog未显示在AsyncTask中

protected void onPreExecute() { 
     super.onPreExecute(); 
     System.out.println("Pre execute began"); 
     exception = null; 
     dialog = new ProgressDialog(context); 
     dialog.setMessage("Loading started"); 
     dialog.setIndeterminate(true); 
     dialog.setCancelable(false); 
     System.out.println("Preexecute end"); 
     dialog.show(); 
    } 

上下文在构造函数中设置:

public Obtainer(Context c, String addr) { 
    context = c; 
    address = addr; 
} 

在运行时,我可以在控制台输出中看到这两个“预执行所开始”和“Preexecute结束”,但进度对话框不显示。问题是什么?

+0

您的代码看起来很好,只知道什么是书籍DOC上下文=新获取器(背景下,URI).execute()得到();?。尝试将 .this而不是上下文... – user370305 2011-12-24 09:25:04

回答

0

使用此代码,它为我工作:

class Obtainer extends AsyncTask<Void, Void, Void> { 
    private ProgressDialog dialog; 

    @Override 
    protected void onPreExecute() { 
     dialog = new ProgressDialog(App.this); // App - your main activity class 
     dialog.setMessage("Please, wait..."); 
     dialog.show(); 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
       // ... 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     dialog.dismiss(); 
    } 

} 

并在您的主要活动类方法调用

new Obtainer().execute(); 
0

什么情况下,当您创建获取器(的AsyncTask子类),你传递?

如果您通过getApplicationContext()使用Application上下文,则无法使用它创建对话框(或任何视图)。您需要将它传递给可以创建视图的上下文。

“如果您习惯使用您的应用程序上下文(例如,从调用getApplicationContext()),例如)需要上下文创建视图的地方,直到找到事情不像你想要或期望的那样工作。“

来源:https://plus.google.com/107708120842840792570/posts/VTeRBsAeyTi