Brandon Stout
Brandon Stout

Reputation: 359

Android Programming: I cannot get data from a background thread AND show a progress dialog

Sorry, the title is a bit hard to understand but I'm not 100% sure as to what to ask. its easier to show you the code and see if you understand from that. I found the way to use the progress dialog from another post on here, so this is basically adding onto that post. ( ProgressDialog not showing until after function finishes ) btw, this is using eclipse environment with the android plugin.

            final MyClass mc = new MyClass(text,info, this);
            final ProgressDialog dialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);

            Thread t = new Thread(new Runnable() 
            {            
                public void run() 
                {
                    // keep sure that this operations
                    // are thread-safe!
                    Looper.prepare(); //I had to include this to prevent force close error

                    mc.doStuff();//does ALOT of stuff and takes about 30 seconds to complete... which is why i want it in a seperate thread

                    runOnUiThread(new Runnable() 
                    {                    
                        @Override
                        public void run() {
                            if(dialog.isShowing())
                                dialog.dismiss();

                        }
                    });
                }
            });
            t.start();

            tmp = mc.getStuff();

now the issue is that tmp is always null because mc isnt finished doing stuff. So, if i do this it finishes doing stuff, but doesnt show the progress dialog..

            t.start();
            while(t.isAlive());//noop
            tmp = mc.getStuff();

Any thoughts or ideas would be greatly appreciated!

Upvotes: 1

Views: 428

Answers (1)

FunkTheMonk
FunkTheMonk

Reputation: 10938

In your second attempt, you are making the main thread wait for the new thread to complete.

The runnable in the runOnUiThread call is where you want to do tmp = mc.getStuff(); That will then be executed on the main thread after mc has finished doStuff().

But otherwise, check out the link blindstuff commented, it simplifies threading.

Upvotes: 1

Related Questions