Question

I am using Parse in my android app and want to block the UI with a dialog while the query runs to get the data. I first create and show a dialog and then do the ParseQuery.find(). However, the dialog never shows up on the UI. Am I missing something?

//Show Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
    builder.setTitle("Some Title...")
    .setMessage("Please wait...")
    .setCancelable(false);
    dialog = builder.create();
    dialog.show();

 List<ParseObject> objects;
        try {
            objects = query.find(); 
            //read is successful
            if (objects != null && objects.size() > 0) {
                    ...........
                    ........
                    dialog.cancel();
    ......................
Was it helpful?

Solution

Yes unfortunately you are missing something.

I am assuming that you are calling your code on the main thread, first dialog.show() and then doing query.find() after that.

Your problem is that you are (probably) doing all this work on the main thread, and the dialog will not show until the main thread has time to parse your .show() command. But since you are blocking the main thread by doing query.find() it won't show until that code has finished executing.

You should solve this problem by doing your query on the background thread, e.g. using AsyncTask, Thread, or some other method.

Let me show you how to do it using thread.

public class MainActivity extends Activity {

    AlertDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Show Dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
        builder.setTitle("Some Title...").setMessage("Please wait...").setCancelable(false);
        dialog = builder.create();
        dialog.show();

        new Thread() {
            public void run() {
                // Do you heavy lifting
                List<ParseObject> objects;
                try {
                    objects = query.find();
                    // read is successful
                    if (objects != null && objects.size() > 0) {

                    }
                } catch (Exception e) {
                }            

                // Since we are in a thread you need to post the cancel on the
                // main thread, otherwise you'll be in trouble.
                runOnUiThread(new Runnable() {
                    public void run() {
                        dialog.cancel();
                    }
                }); 
            }
        }.start();
    }
}

Hopefully you'll find my answer helpful!

Best Regards, Erik

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