加载互联网时显示对话框

时间:2015-02-27 01:03:57

标签: android android-asynctask dialog httprequest

我正在尝试在加载Httprequest时创建一个对话框。但它在我点击上次活动的意图期间加载,但不是此活动的开始。

然后在0.00001秒中显示的对话框就会消失。

我是否错误地实施了它?

这是我的代码

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    HttpPostHandler2 handler = new HttpPostHandler2();
    String URL ="http://xxxxxx";        
    handler.execute(URL);
}

public class HttpPostHandler2 extends AsyncTask<String, Void, String> {

    private String resultJSONString = null;
    private ProgressDialog pDialog;

    public String getResultJSONString() {
        return resultJSONString;
    }

    public void setResultJSONString(String resultJSONString) {
        this.resultJSONString = resultJSONString;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please Wait");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        CredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,
                AuthScope.ANY_PORT), new UsernamePasswordCredentials("core",
                "core1234"));
        String responseContent = "";

        HttpClient httpClient = new DefaultHttpClient();
        ((AbstractHttpClient) httpClient).setCredentialsProvider(credProvider);
        HttpPost httpPost = new HttpPost(params[0]);

        HttpResponse response = null;
        try {
            // Execute HTTP Post Request
            response = httpClient.execute(httpPost);
            responseContent = EntityUtils.toString(response.getEntity());
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        setResultJSONString(responseContent);
        // return new JSONObject(responseContent);
        return responseContent;
    }

    @Override
    protected void onPostExecute(String result) {
        pDialog.dismiss();  
        super.onPostExecute(result);
        resultJSONString = result;
    }
}

1 个答案:

答案 0 :(得分:1)

确保HttpPostHandler2的工作足够长,以显示pDialog。如果不是,它很快就会消失。 但是,您无法在onCreate中显示GUI。要显示对话框,您应将其移至onStart

@Override
public void onCreate(Bundle savedInstanceState) {//GUI not ready: nothing is shown
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  HttpPostHandler2 handler = new HttpPostHandler2();

}

@Override
protected void onStart () {//GUI is ready
   String URL ="http://xxxxxx";
   handler.execute(URL);
}

有关详细信息,请参阅评论。