How do I run my code after the Activity is visible?

I have an activity with 3 spinners. These spinners get their data from the web service in a method that takes about 1 minute.

I want to load the activity first and after it becomes visible, call this method of the web service and load the data. I tested the following codes separately but none of them solved my problem. In these examples, the application goes to a black screen, and when the web service operation is complete, it becomes visible.

@Override
protected void onCreate() {

    //.........    


    final Runnable r = new Runnable()
    {
        public void run()
        {
            loadMyData();
        }
    };
    Utilities.performOnBackgroundThread(r);    
}

      


@Override
protected void onResume() {

    new Thread() {
        @Override
        public void run() {
            loadMyData();
        }
    }.start();
    super.onResume();

}

      


@Override
protected void onStart() {
    if (comesFromOnCreateMethod)
    {
        final Runnable r = new Runnable()
        {
            public void run()
            {
                loadMyData();
            }
        };
        Utilities.performOnBackgroundThread(r);
    }
    comesFromOnCreateMethod = false;
    super.onStart();
}

      


@Override
protected void onResume() {

    if (comesFromOnCreateMethod)
    {
        final Runnable r = new Runnable()
        {
            public void run()
            {
                loadMyData();
            }
        };
        Utilities.performOnBackgroundThread(r);
    }
    comesFromOnCreateMethod = false;

}

      

+3


source to share


4 answers


If you are getting a black screen, I would assume that your code is running on the UI thread and not in the background, causing the UI to hang until the job is done.

One of the best solutions for background work is AsyncTask . Using this, you can call it in your onCreate () method, and when it's done, it will send a callback to the UI thread for you, where you can display the data.



If you want this method to run every time this Activity is displayed, then call it in onResume (). Otherwise, call it in onCreate ().

+4


source


In your onCreate do asynchronous tasks as others have reported. Make sure you create content for the app first and then call asyncTasks. You can control the spinners from a callback.



+2


source


First of all, you can increase the acceptance rate, 39% is quite low.

Anyway, you can check AsyncTask, it should do it. http://developer.android.com/reference/android/os/AsyncTask.html

Typically, you want to initialize inPreExecute, create a network in doInBackGround, and set the result on the UI thread to OnPostExecute. Hope this helps.

+1


source


Use AssynchTask()

and you must summon super. onResume()

or any lifecycle method in the corresponding lifecycle method first and then another specific method you want to do ....

+1


source







All Articles