开发者

Android ProgressDialog runtime exception error

开发者 https://www.devze.com 2023-02-18 02:33 出处:网络
I\'m having trouble trying to put a ProgressDialog into my app. In my GameEngine class (which doesn\'t extend anything), I have the code shown below. The first line produces 开发者_如何学运维a runtime

I'm having trouble trying to put a ProgressDialog into my app. In my GameEngine class (which doesn't extend anything), I have the code shown below. The first line produces 开发者_如何学运维a runtime exception, and although I came across this thread that seems to be about the same error: Android TimerTask throws RuntimeException if Show ProgressDialog is added in run(), I don't really understand how to implement the solution. Any help would be much appreciated, thanks.

    //Create ProgressDialog
    ProgressDialog dialog = ProgressDialog.show(context, "", 
            "Loading...", true);

    //Set Clusters before level starts
    for (int i = 0; i < 80; i++)
    {
        updateBacteria();
        updateAttraction();
        checkCollisions();
        moveObjectsAwayFromWalls();
    }

    dialog.dismiss();


You can only show dialogs in the UI thread (which is your main class which extends Activity). To be able to do this, you can write a Handler and use it to send messages from the non UI thread to the UI thread. Android have an example of this in their ProgressDialog example. View the snippet of code they have under "Example ProgressDialog with a second thread".

You can also follow the same method as written in the answer of the link you provided, although a Handler is a more robust approach.


If this method is not running in your Main Activity thread, you should change it. how? Set a Handler in the main activity and pass it to the thread (above). In the handler you should implement the GUI related part of your method (i.e. ProgressDialog). When you need to show the ProgressDialog, just call your Handler and than keep processing (your loop in this case). Same for the dismiss().

0

精彩评论

暂无评论...
验证码 换一张
取 消