android: displaying progress dialog when waiting for connection

安稳与你 提交于 2019-12-04 16:51:16
Walid Hossain

You should use Progress dialog. Progress dialog should be used in the Profile activity. You can use the following code:

    final ProgressDialog dialog = ProgressDialog.show(MyProfileActivity.this, "","Loading..Wait.." , true);
dialog.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
        //your code here
                dialog.dismiss();
    }   
}, 3000);  // 3000 milliseconds

Doing network calls in the UI thread (the thread which calls "onCreate") is a bad idea. It will stall the refresh of the UI till the network operation is completed. Instead, spawn a new thread in onCreate like so:

Thread networkThread = new Thread() {
    public void run() {

        String xml = XMLfunctions.getXMLFromBarId(id); // makes httpPost call
        Document doc = XMLfunctions.XMLfromString(xml);
        NodeList nodes = doc.getElementsByTagName("result");
        Element e = (Element)nodes.item(0);

        ....
   }
}
networkThread.start();

Also, I'd recommend using a ProgressDialog to show progress (which you can dismiss, once the code in the thread is done). Tutorial: http://developer.android.com/guide/topics/ui/dialogs.html

Note: You cannot dismiss the dialog from the new thread, so you will have to use a Handler to post a message from the thread to the UI thread. Here a tutorial for that: http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html

Example: In your Profile activity class, add this:

class ProfileActivity extends Activity {
    class ProfileHandler extends Handler {
        private ProfileActivity parent;

        public ProfileHandler(ProfileActivity parent) {
            this.parent = parent;
        }

        public void handleMessage(Message msg) {
            parent.handleMessage(msg);
        }
    }

    private ProfileHandler handler;

    public void onCreate(Bundle savedInstanceState) {
        handler = new ProfileHandler(this);

        Thread networkThread = new Thread() {
            public void run() {

            String xml = XMLfunctions.getXMLFromBarId(id); // makes httpPost call
            Document doc = XMLfunctions.XMLfromString(xml);
            NodeList nodes = doc.getElementsByTagName("result");
            Element e = (Element)nodes.item(0);

            ....

            ProfileActivity.this.handler.sendEmptyMessage(0);
            }
        }
        networkThread.start();
    }

    public void handleMessage(msg) {
        switch(msg.what) {
        case 0:
            // Update UI here
            break;
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!