Search code examples
androidmultithreadingandroid-asynctaskprogressdialogrunnable

Android Progress Dialog Box While updating GUI


So I've been at this for 2 days and still I can't get it working. I've tried solutions of implementing runnable, asynctask but it just never seems to work with my code. Perhaps I implemented it the wrong way...

Anyway, I have the following code written. When I create this activity I want to show a progressdialog with the text "Loading". Problem is, you can't update GUI-elements from another thread. That is where I'm stuck. Hope you can help me out!

PS: The reason i need a ProgressDialog is because the line

ArrayList<String> genres = MysqlHandler.getAllGenres();

Can take quite some time to load. Also i have some other activities which need to do the same, and there it can take up to 5 seconds to load.

public class GenreActivity extends Activity implements OnClickListener {

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

    try {
        ArrayList<String> genres = MysqlHandler.getAllGenres();

        LinearLayout layout = (LinearLayout) findViewById(R.id.AllGenreLayout);

        for(int i = 0; i < genres.size(); i++)
        {
            Button myButton = new Button(this);
            myButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.yellow_button));
            myButton.setTextAppearance(this, R.style.ButtonText);
            myButton.setText(genres.get(i));
            myButton.setOnClickListener(this);
            layout.addView(myButton);
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Solution

  • I found a work-around and thought I would share it. Since I was making another thread inside the oncreate method, I figured I could also make a thread when i was starting the intent. So instead of this code:

    Intent inte = new Intent(FirstSearchActivity.this, GenreActivity.class);
    startActivity(inte);
    

    Now I'm doing:

    //start the progress dialog
    progressDialog = ProgressDialog.show(FirstSearchActivity.this, "", "Loading...");
    new Thread() 
    {
    public void run() 
        {
            Intent inte = new Intent(FirstSearchActivity.this, GenreActivity.class);
            startActivity(inte);
            progressDialog.dismiss();
        }
    }.start();