Question

I want to show a progress bar in my activity which contains code to test server connection using socket. I want my progress bar to be visible only when sending data to server. As soon as i got reply from server, the progress should be dismissed and shows Alert box with message "Server busy". but in my screen the progress bar is visible after getting reply from server.Here is my code .

 public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            mProgress = (ProgressBar) findViewById(R.id.progressBar1);
            mProgress.setProgress(0);
            checkdb();
        }
    private void checkdb() {        
            String message = "";
            try {

                serverIpAddress = InetAddress.getByName("192.168.1.133");

                Log.d("TCP", "C: Connecting...");
                socketObject = new Socket(serverIpAddress, 8221);
                String str = "hi";
                try {
                    Log.d("TCP", "C: Sending: '" + str + "'");
                    PrintWriter out = new PrintWriter(new BufferedWriter(
                            new OutputStreamWriter(socketObject.getOutputStream())), true);
                    out.println(str);

                    inputStream = socketObject.getInputStream();

                    inputDataStream = new DataInputStream(inputStream);

                    message = inputDataStream.readUTF();
                    Log.d("TCP", "C: Reply: '" + message + "'");
                } 
                catch(IOException e)
                {

                    Log.e("TCP", "S: Error", e);
                }catch (Exception e) {

                    Log.e("TCP", "S: Error", e);
                }

                finally {

                    socketObject.close();
                    Log.e("TCP", "S: Error");
                }

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                Log.e("TCP", "C: UnknownHostException", e);
                e.printStackTrace();
            } 
            catch(IOException e)
            {

                Log.e("TCP", "S: Error:", e);

             //Code to show Alert box with message "IOException"

            }
        }

so what should be done to have my progress bar to be visible before i get reply from server. If i get reply, the progress bar should be dismissed. Any one please help me...

Was it helpful?

Solution

Here is how I have implemented progressbar while authenticating a user using AsyncTask. See if this can help you

        private class LoginTask extends AsyncTask<String, Integer, Boolean>{
    private final ProgressDialog dialog = new ProgressDialog(LoginActivity.this);
    public LoginTask(LoginActivity activity) {   

    } 

    @Override 
    protected void onPreExecute() { 
        this.dialog.setMessage("Please wait.."); 
        this.dialog.setIndeterminate(true) ;
        this.dialog.setCancelable(false);
        this.dialog.show();  
        } 


    @Override
    protected Boolean doInBackground(String... params) {
        try {
            Thread.sleep(5000); //Execute long running task
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    @Override
    protected void onPostExecute(Boolean result) { 
        if (this.dialog.isShowing()) {            this.dialog.dismiss();         }
        LoginActivity.this.processAuthenticationResult(result.booleanValue());
    }

}   

And called this from my LoginActivity as below

 new LoginTask(LoginActivity.this).execute(new String[]{userName, password});

OTHER TIPS

Just use mProgress.setVisibility(View.GONE) or mProgress.setVisibility(View.VISIBLE) to hide and show your widget.

To avoid that your main user activity gets blocked you need to do the connection part in a separate thread and use a Handler to update it. The code would be sth like:

In the connection thread to inform the UI activity...

mHandler.obtainMessage(Main_screen.MESSAGE_PGROGRESS_CHANGE_UPDATE, state, -1)
    .sendToTarget();

In the UI activity:

 private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if (DEBUG)
        Log.i(this.getClass().getSimpleName(),
            "-> "
                + Thread.currentThread().getStackTrace()[2]
                    .getMethodName());
        switch (msg.what) {
        case MESSAGE_PGROGRESS_CHANGE_UPDATE:
        if (DEBUG)
            Log.i(this.getClass().getSimpleName(),
                "  MESSAGE_PGROGRESS_CHANGE_UPDATE: " + msg.arg1);

        // do your update of progressbar or whatever here
        break;
            case MESSAGE_PGROGRESS_CHANGE_SYNCHRINIZATION:
        if (DEBUG)
            Log.i(this.getClass().getSimpleName(),
                "  MESSAGE_PGROGRESS_CHANGE_SYNCHRINIZATION: " + msg.arg1);

        // do your update of progressbar or whatever here
        break;

HI You can use AsynTask for doing severcommunication in background and display the result to screen. I hope this code helps you.

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


    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

        // showDialog("Fetching Video Url........");
        favDialog = new Dialog(PlasmaView.this,
                android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);

        favDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        favDialog.getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        favDialog.setContentView(R.layout.busypopup);

        loadMessage = (TextView) favDialog
                .findViewById(R.id.loadingmessgetext);

        loadMessage.setText("Communicating with server........");

        favDialog.setCancelable(false);

        try {
            favDialog.show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.info("Dialog " + e.getMessage());
        }

    }

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

        String message = "";
        try {

            serverIpAddress = InetAddress.getByName("192.168.1.133");

            Log.d("TCP", "C: Connecting...");
            socketObject = new Socket(serverIpAddress, 8221);
            String str = "hi";
            try {
                Log.d("TCP", "C: Sending: '" + str + "'");
                PrintWriter out = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(socketObject.getOutputStream())), true);
                out.println(str);

                inputStream = socketObject.getInputStream();

                inputDataStream = new DataInputStream(inputStream);

                message = inputDataStream.readUTF();
                Log.d("TCP", "C: Reply: '" + message + "'");

            } 
            catch(IOException e)
            {

                Log.e("TCP", "S: Error", e);
            }catch (Exception e) {

                Log.e("TCP", "S: Error", e);
            }

            finally {

                socketObject.close();
                Log.e("TCP", "S: Error");
            }

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            Log.e("TCP", "C: UnknownHostException", e);
            e.printStackTrace();
        } 
        catch(IOException e)
        {

            Log.e("TCP", "S: Error:", e);

         //Code to show Alert box with message "IOException"

        }
return message;
    }

    @Override
    protected void onPostExecute(String result) {

        try {
            if (favDialog.isShowing()) {
                favDialog.dismiss();
                favDialog = null;
            }
        } catch (Exception e1) {

        }
    Toast.makeText(YourScreen.this, result, Toast.LENGTH_LONG).show();


        super.onPostExecute(result);

    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top