manf
manf

Reputation: 55

Bring up Dialogs directly?

I have the following Code for a Button, which i want to built up a Socket Connection and then try to send data over the Network. When i have no Server for the Socket it takes a few seconds before the App recognizes and i get an error. In this time the App do nothing (as u could expect) to have a simple Notification for the User to show him the App is not broken, i want to bring up a little ProgressBar.

private void sendButtonListener(Button sendButton, final String server,
        final int port) {
    sendButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            refreshInput();

            showDialog(DIALOG_CONNECTING);
            //Getting the SocketConnection and try to send the Data
            attempToSendXML(builder, profilename);
            dismissDialog(DIALOG_CONNECTING);
        }
    });
}

My Problem is that it seems that the showDialog() Method is brings up the ProgressBar after the onClick(View v) Method is finished. So for my example it shows just nothing (it just hangs until the the attempToSendXML() method is finished), because i close the Dialog after i tried to send the Data.

I hope u guys get my Point and can help me. I've been looking around for 2 hours now and really don't get it ...

Upvotes: 0

Views: 57

Answers (1)

js-
js-

Reputation: 1632

You should not block the UI thread with a long operation like attempToSendXML().

Instead you should use an AsyncTask. The AsyncTask should be the solution to your problem as well.

See here and here.

The AsyncTask has an onPreExecute()-method where you show up your dialog. attempToSendXML() will then be executed in the method doInBackground and the dialog is closed in the method onPostExecute of the AsyncTask. By doing it this way you do not block the UI-Thread (and get no ANR exception) and the progress dialog shows a long as the operation is working in the background.

Upvotes: 1

Related Questions