Ben Ghaleb
Ben Ghaleb

Reputation: 483

AlertDialog is shown before methods insde thread finished Android Java

The first activity in the app checks if tables and data are loaded correctly before launching the main activity.

If not, it connects to server using volley and loads the data and images and then asks user to restart app.

The problem is: AlertDialog is shown with "message loading complete" directly before the methods finished loading.

I created a thread inside the onCreate method and put all methods inside it but the same problem persists.

My question is: How can I show the alertDialog after methods complete data loading?

Here is my code:

    if(! (checkTables()&&checkData())){
        progressDialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {

                fillSamples();
                fillExams();
                fillQuestions();
                fillSubQuestions();
            }
        }).start();
        progressDialog.dismiss();
        AlertDialog.Builder builder=new AlertDialog.Builder(SplashScreen.this);
        builder.setMessage("Loading Data Complete Please restart your App");
        builder.setCancelable(false);
        builder.setPositiveButton("Restart", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                System.exit(1);
            }
        });
        AlertDialog dialog=builder.create();
        dialog.show();
    }

Upvotes: 1

Views: 111

Answers (1)

Archana
Archana

Reputation: 637

Try to use AsyncTask instead of Thread. For more info Threads and AsyncTask

if(! (checkTables()&&checkData())){
    GetData.execute();
}
class GetData extends AsyncTask<Void, Void,Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //Add your progress dialog.
        progressDialog.show();
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
            AlertDialog.Builder builder=new AlertDialog.Builder(SplashScreen.this);
            builder.setMessage("Loading Data Complete Please restart your App");
            builder.setCancelable(false);
            builder.setPositiveButton("Restart", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    System.exit(1);
                }
            });
            AlertDialog dialog=builder.create();
            dialog.show();
        }
    }

    @Override
    protected Void doInBackground(Void... voids) {
        fillSamples();
        fillExams();
        fillQuestions();
        fillSubQuestions();
        return null;

    }
}

Upvotes: 1

Related Questions