Question

I have an Activity with 3 spinners. These spinners get their data from a web-service by a method that takes about 1 minute to be completed.

I want to load the Activity first and after it is made visible, call that web-service method and load data. I have tested the following codes separately but none of them solved my problem. In these samples application goes into a black screen and when the web-service operation completed, it is made 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;

}
Was it helpful?

Solution

If you are getting a black screen, then I would assume your code is being run on the UI thread and not on the background, causing the UI to hang until the work is completed.

One of the best solutions to doing background work is an AsyncTask. Using this, you can call it in your onCreate() method, and when its done, it will post a callback to the UI thread for you in which you can display you data.

If you want this method to run everytime this Activity displays, then call it in onResume(). Otherwise, call it in onCreate().

OTHER TIPS

In your onCreate, make the async tasks as the others have advised. Make sure you generate the content for the app first and then call the asyncTasks. You can control your spinners from the callback.

First of all, you might want to increase your accept rate, 39% is pretty low.

Anyway, you might want to check AsyncTask, it should do the thing. http://developer.android.com/reference/android/os/AsyncTask.html

Typically, you will want to initialize in onPreExecute, do the networking in the doInBackGround, and set the result to the UI thread on the OnPostExecute. Hope this will help.

Use AssynchTask() and you should call super.onResume() or any lifecycle method in respective life cycle method first then other specific method you want to do....

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