Search code examples
androidprogressdialog

How to show a ProgressDialog while changing from a activity to another activity?


i want to show a PD when my activity A starts another activity B. But in that onclick method, my A activity haves to do some work before start B, and B also haves to do some work because it haves to load a lot of data for the UI.

I need a PD that is viewed by the user in all the process of the loading data of changin from activity A to B.

¿how can do it?

i tryed storing a static ProgressDialog on MyApplication.java, and with these methods:

public static void showProgressDialog(Context c) {
    pd = ProgressDialog.show(c, c.getResources().getString(R.string.app_name), 
        c.getResources().getString(R.string.loading), true, false);    
}
public static void dismissProgressDialog(){
    pd.dismiss();
}

but it doesn't works, it doesn't shows nothing, i dont know why

how to achieve this by a easy way? i know that i can do it with async task, but that is too hard for me, i can't understand the code examples i am finding on this web and google

code examples are welcome

thanks


Solution

  • well, i agree with @Falmarri comment, the easy way is implementing that with an AsyncTask. Because AsyncTask manages the UIThread and a background thread.

    i always do this with AsyncTask but i don´t think that paste here my code will help you, because your requirements maybe are not like mine, but i think you can do in this way;

    Subclass the AsyncTask and override these methods;

    • onPreExecute()... because this method is invoked in the ui thread you can create and show the progress dialog.
    • doInBackground(Runnable task)... this method run in a background thread so you don´t have to worry about Threads handling... all you have to do is the hard work
      (process data, download data, etc)
      and publish any update to the ui that you want.

    • onProgressUpdate(Object... values)... this method also is called in the ui thread, so you can update your
      progress dialog with the progress
      values.

    • onPostExecute(Object result)... this method run in the ui thread so, you can show the operation
      result and dismiss the progress
      dialog, and invoke your new activity.

    you can do all operations here, the activity A operation and activity B operation, and the AsynTask will manage for you the Threading management :)

    Edit 1:

    i don't know how much complex is your desing but here i make a project example, maybe it's not what you want but it has all stuff decribed here, in my answer, maybe like an example works.

    i suggest that you read more about this class because is one of the most important, here you can read more about this mechanism... http://android-developers.blogspot.com/2009/05/painless-threading.html