1

I try to make a ProgressDialog that shows the user the progress of connecting with a Bluetooth device but my progress dialog stays at 0% and the Bluetooth device doesn't connect. When I call the functions in onCreate() it connects but I won't have a ProgressDialog when I do that.

I don't know what to do!

PLEASE HELP!

This is my code

public void StartConnection(){
    loading = new ProgressDialog(this);
    loading.setTitle("Loading connection...");
    loading.setMessage("Loading...");
    loading.setProgressStyle(loading.STYLE_HORIZONTAL);
    loading.setProgress(0);
    loading.setMax(100);
    loading.show();

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                //Get device ID
                loading.setProgress(0);
                loading.setMessage("Getting device ID...");
                try {
                    getDeviceId();
                } catch (Exception ex) {
                    ErrorMessage("Couldn't get device ID");
                    ErrorAlert += "Error 101: Couldn't get device ID\n";
                }
                Thread.sleep(2000);
                loading.setProgress(20);

                //Open connection
                loading.setMessage("Opening connection...");
                try{
                    openConnection();
                } catch (IOException ex){
                    ErrorMessage("Couldn't open connection");
                    ErrorAlert += "Error 102: Couldn't open connection\n";
                }
                Thread.sleep(2000);
                loading.setProgress(40);

                //Testing connection
                loading.setMessage("Testing connection...");
                if (!mmSocket.isConnected()){
                    ErrorMessage("Test failed!");
                    ErrorAlert += "Error 103: Test failed!\n";
                }
                Thread.sleep(2000);
                loading.setProgress(60);

                //Calibrate sensors
                loading.setMessage("Calibrating sensors...");
                try{
                    sendCommand("c");
                }catch (IOException ex){
                    ErrorMessage("Couldn't calibrate sensors");
                    ErrorAlert += "Error 104: Couldn't calibrate sensors\n";
                }
                Thread.sleep(2000);
                loading.setProgress(80);

                //Finish
                loading.setMessage("Finishing...");
                Thread.sleep(1000);
                loading.setProgress(90);

                //Clear
                loading.setMessage("Clearing some stuff...");
                Thread.sleep(1000);
                loading.setProgress(100);

                if (loading.getProgress() == loading.getMax()) {
                    loading.dismiss();
                    Toast.makeText(getApplicationContext(), "Finished, connection is established", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {

            }
        }
    }).start();

}

Edit: I think this is the problem:

03-05 19:34:28.342 3488-3488/com.jules_citronic.racecarcontrol E/ActivityThread: Performing stop of activity that is not resumed: {com.jules_citronic.racecarcontrol/com.jules_citronic.racecarcontrol.Menu}
                                                                             java.lang.RuntimeException: Performing stop of activity that is not resumed: {com.jules_citronic.racecarcontrol/com.jules_citronic.racecarcontrol.Menu}
                                                                                 at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3509)
                                                                                 at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3594)
                                                                                 at android.app.ActivityThread.-wrap20(ActivityThread.java)
                                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1392)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                 at android.os.Looper.loop(Looper.java:148)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:5466)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Edit: I tried to apply the you suggestion but i gives this error:

AndroidStudio gives an error

Edit: Eh, stil doesn't work :(

First

Here is the whole function:

private void StartConnection(){
    loading = new ProgressDialog(this);
    loading.setTitle("Loading connection...");
    loading.setMessage("Loading...");
    loading.setProgressStyle(loading.STYLE_HORIZONTAL);
    loading.setProgress(0);
    loading.setMax(100);
    loading.show();

    new Thread( runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                //Get device ID
                loading.setProgress(0);
                loading.setMessage("Getting device ID...");
                try {
                    getDeviceId();
                } catch (Exception ex) {
                    ErrorMessage("Couldn't get device ID");
                    ErrorAlert += "Error 101: Couldn't get device ID\n";
                }
                Thread.sleep(2000);
                loading.setProgress(20);

                //Open connection
                loading.setMessage("Opening connection...");
                try {
                    openConnection();
                } catch (IOException ex) {
                    ErrorMessage("Couldn't open connection");
                    ErrorAlert += "Error 102: Couldn't open connection\n";
                }
                Thread.sleep(2000);
                loading.setProgress(40);

                //Testing connection
                loading.setMessage("Testing connection...");
                if (!mmSocket.isConnected()) {
                    ErrorMessage("Test failed!");
                    ErrorAlert += "Error 103: Test failed!\n";
                }
                Thread.sleep(2000);
                loading.setProgress(60);

                //Calibrate sensors
                loading.setMessage("Calibrating sensors...");
                try {
                    sendCommand("c");
                } catch (IOException ex) {
                    ErrorMessage("Couldn't calibrate sensors");
                    ErrorAlert += "Error 104: Couldn't calibrate sensors\n";
                }
                Thread.sleep(2000);
                loading.setProgress(80);

                //Finish
                loading.setMessage("Finishing...");
                Thread.sleep(1000);
                loading.setProgress(90);

                //Clear
                loading.setMessage("Clearing some stuff...");
                Thread.sleep(1000);
                loading.setProgress(100);

                if (loading.getProgress() == loading.getMax()) {
                    loading.dismiss();
                    Toast.makeText(getApplicationContext(), "Finished, connection is established", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {

            }
        }
    })).start();
}

Edit: Fixed the runOnUiThread:

private void StartConnection(){
    loading = new ProgressDialog(this);
    loading.setTitle("Loading connection...");
    loading.setMessage("Loading...");
    loading.setProgressStyle(loading.STYLE_HORIZONTAL);
    loading.setProgress(0);
    loading.setMax(100);
    loading.show();

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                //Get device ID
                loading.setProgress(0);
                loading.setMessage("Getting device ID...");
                try {
                    getDeviceId();
                } catch (Exception ex) {
                    ErrorMessage("Couldn't get device ID");
                    ErrorAlert += "Error 101: Couldn't get device ID\n";
                }
                Thread.sleep(2000);
                loading.setProgress(20);

                //Open connection
                loading.setMessage("Opening connection...");
                try {
                    openConnection();
                } catch (IOException ex) {
                    ErrorMessage("Couldn't open connection");
                    ErrorAlert += "Error 102: Couldn't open connection\n";
                }
                Thread.sleep(2000);
                loading.setProgress(40);

                //Testing connection
                loading.setMessage("Testing connection...");
                if (!mmSocket.isConnected()) {
                    ErrorMessage("Test failed!");
                    ErrorAlert += "Error 103: Test failed!\n";
                }
                Thread.sleep(2000);
                loading.setProgress(60);

                //Calibrate sensors
                loading.setMessage("Calibrating sensors...");
                try {
                    sendCommand("c");
                } catch (IOException ex) {
                    ErrorMessage("Couldn't calibrate sensors");
                    ErrorAlert += "Error 104: Couldn't calibrate sensors\n";
                }
                Thread.sleep(2000);
                loading.setProgress(80);

                //Finish
                loading.setMessage("Finishing...");
                Thread.sleep(1000);
                loading.setProgress(90);

                //Clear
                loading.setMessage("Clearing some stuff...");
                Thread.sleep(1000);
                loading.setProgress(100);

                if (loading.getProgress() == loading.getMax()) {
                    loading.dismiss();
                    Toast.makeText(getApplicationContext(), "Finished, connection is established", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {

            }
        }
    });
}

But now the ProgressDialog doesn't appear at all.:( When I click on the button that starts the activity, the screen goes black and freezes, when the Bluetooth connects, it loads the layout. Never showed a ProgressDialog.

Jules Hummelink
  • 584
  • 1
  • 6
  • 14
  • Use runOnUiThread method as mentioned in the link : [http://stackoverflow.com/a/11140429/5207572](http://stackoverflow.com/a/11140429/5207572) – Nabil Sunesara Mar 05 '16 at 19:15

2 Answers2

0

I think you wish to update ProgressDialog from a new Thread but it was created on UI thread. You can't do that. See your IDE's output logs. Take a look on this link to add runOnUiThread method.

It works on OnCreate because the code is executed by UI thread.

Community
  • 1
  • 1
L Kudo
  • 1
  • 1
  • 1
  • 3
  • wrap your runnable instance with runOnUiThread like this : new Thread( runOnUiThread(new Runnable() { // run function }); ).start(); – L Kudo Mar 05 '16 at 19:27
  • sorry, delete the semicolon... the error on Runnable disappear when you add the override function : new Thread( runOnUiThread(new Runnable() { @Override public void run() { // your code } }) ).start(); – L Kudo Mar 05 '16 at 20:37
  • Fixed it, but now the ProgressDialog doesn't appear at all.:( When I click on the button that starts the activity, the screen goes black and freezes, when the Bluetooth connects, it loads the layout. Never showed a ProgressDialog. – Jules Hummelink Mar 05 '16 at 21:09
0

Android itself contains a great API for background processes which need to interact with the main UI thread.AsyncTask is the way to go for that, it will save you all the heavy lifting making all threading operations very easy for you (internally uses Thread, Handler, Executor, ThreadPoolExecutor and FutureTask among others).

Check this example and you will make it work in few steps.

All you need to know is this main concepts of AsyncTask helper:

When an asynchronous task is executed, the task goes through 4 steps:

1 - onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

2 - doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

3 - onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

4 - onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Community
  • 1
  • 1
GoRoS
  • 5,183
  • 2
  • 43
  • 66
  • This is a little bit beyond my java skills, can you edit my script?? Thanx ;) – Jules Hummelink Mar 05 '16 at 21:47
  • Sorry @JulesHummelink I cannot do that for you, the reference http://developer.android.com/reference/android/os/AsyncTask.html is written for dummies. There is even an example called `DownloadFilesTask` where they use the `onProgressUpdate` method to update the progressView as you do with `loading.setProgress(0);`. You should at least try to read and code it, there is no any other way to improve your Java skills. If I write it out for you, you won't make any step forward, trust me. – GoRoS Mar 05 '16 at 22:22