Search code examples
androidmultithreadinglooper

Android additional threads and Looper


I am writing a Android application which reads data from a SQLite Database and then displays the data on a next screen. Whenever I was doing a query on the database I would get an error message that too much work is being done on the main thread.

I then put my query in a new Thread:

        (new Thread()
        {
            public void run()
            {
                Looper.prepare();
                try
                {
                    FPJobCardWizard data = dbHelperInstance.loadFPJobCardWizardFull(fitmentHash);
                    wState.fitmentItemSet(data.fitmentItemGet());
                } catch (Exception e) {e.printStackTrace();}
                Looper.loop();
            }
        }).start();

Now the gui/main thread is completing it's operation prior to the Query being complete and as a result the data variable is still empty. I read a few posts and the API documentation and it seems that I need to use a Looper (this seems to be the correct fix) but I have never used a Looper and cannot seem to get it to work.

Please can you check the code above and guide me in the right direction.

Thank you all in advance.


Solution

  • the best choice here will be using an AsyncTask, as it will enables you to perform all the background work in a background thread, then when the result is generated it will apply it using the UI thread:

    AsyncTask life cycle

    So, as explained in the life cycle of AsyncTask, you can do all of your background work in the method doInBackground() and then do all of your UI work on the method onPostExecute() which will be executed after taking the result from doInBackground() method according to the life cycle, and to put your hands more on the AsyncTask, have a look at this example which provides the following example code:

    public class AsyncTaskTestActivity extends Activity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);  
    
            // This starts the AsyncTask
            // Doesn't need to be in onCreate()
            new MyTask().execute("my string paramater");
        }
    
        // Here is the AsyncTask class:
        //
        // AsyncTask<Params, Progress, Result>.
        //    Params – the type (Object/primitive) you pass to the AsyncTask from .execute() 
        //    Progress – the type that gets passed to onProgressUpdate()
        //    Result – the type returns from doInBackground()
        // Any of them can be String, Integer, Void, etc. 
    
        private class MyTask extends AsyncTask<String, Integer, String> {
    
            // Runs in UI before background thread is called
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
    
                // Do something like display a progress bar
            }
    
            // This is run in a background thread
            @Override
            protected String doInBackground(String... params) {
                // get the string from params, which is an array
                String myString = params[0];
    
                // Do something that takes a long time, for example:
                for (int i = 0; i <= 100; i++) {
    
                    // Do things
    
                    // Call this to update your progress
                    publishProgress(i);
                }
    
                return "this string is passed to onPostExecute";
            }
    
            // This is called from background thread but runs in UI
            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
    
                // Do things like update the progress bar
            }
    
            // This runs in UI when background thread finishes
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
    
                // Do things like hide the progress bar or change a TextView
            }
        }
    }