Skip to content Skip to sidebar Skip to footer

Need More Understanding Of Asynctask In Android

I have this line of code which has no problem at all, the only issue is that every time this code is executed the app waits for all the process to finish making the interface not r

Solution 1:

If you perform a long lasting operation, e.g. loading a file or accessing data , the user interface of your Android Application will block until the corresonding code has finished.

AsyncTask

In order to use the AsyncTask class, you must extend it and override at least the doInBackground() method.

The most common methods you will need to implement are these:

1. onPreExecute() – called on the UI thread before the thread starts running. This method is usually used to setup the task, for example by displaying a progress bar.

   2. doInBackground(Params…) – this is the method that runs on the background thread. In this method you should put all the code you want the application to perform in background. Referring to our Simple RSS Aplication, you would put here the code that downloads the XML feed and does the parsing. The doInBackground() is called immediately after onPreExecute(). When it finishes, it sends the result to the onPostExecute().

   3. onProgressUpdate() - called when you invoke publishProgress() in the doInBackground().

   4. onPostExecute(Result) – called on the UI thread after the background thread finishes. It takes as parameter the result received from doInBackground().

Now In your code selection ,what you can do.

All database Operation and data manipulation code are write in doInBackground(Params…) method and show data in onPostExecute(Result) method.

Thanks.

Solution 2:

Basically you need to extend the AsyncTask class and make your own implementation. You make use of the fact that the doInBackground() function runs in a non-UI thread, and the result it returns you can use in onPostExecute() function which runs in the UI thread.

You mentioned that your code calls a database, so I'm gonna assume that your "startmoving" object is the database module. I'm gonna just call it MovingDb class for the example code below, since it's not shown in your code what the actual class name is.

// this will hold all your calculated valueprivateclassDisplayInfo {
   String displayName, displayValue, displayWeight, displayTotalWeight, displayRoomWeight;
   int displayTotalItem;
}

privateclassItemHolderTaskextendsAsyncTask<MovingDb, Integer, DisplayInfo> {

   protected DisplayInfo doInBackground(MovingDb... movingDbs) {
      // this code runs in background thread so do your DB work hereif (movingDbs != null && movingDbs.length > 0 && movingDbs[0] != null) {
         MovingDbstartMoving= movingDbs[0];
         // move all your db operations hereStringcurrentItemHolder= startMoving.getSingleIteName(....)
         // blah blahDisplayInfodisplayInfo=newDisplayInfo();
         displayInfo.displayName = startMoving.getItemName(...);
         displayInfo.displayValue = startMoving.getItemValue(...);
         // set up the rest of your display info valuesreturn displayInfo;
      }
   }

   protectedvoidonPostExecute(DisplayInfo displayInfo) {
      // the displayInfo you return from doInBackground comes hereif (displayInfo != null) {
         roomContent.setText(displayInfo.displayName);
         itemValue.setText(displayInfo.displayValue);
         // and so on...
      }
   }
}

and in your onClick function, you'll just start the ItemHolderTask:

new ItemHolderTask().execute(startMoving);

Solution 3:

The AsyncTask executes everything in doInBackground() inside of another thread, which does not have access to the GUI where your views are.

preExecute() and postExecute() offer you access to GUI before and after the heavy lifting occurs in this new thread, you can even pass the result of the long operation to postExecute() to then show any results of processing.

Android modifies the user interface via one thread, the so called UI Thread. If you perform a long running operation directly on the UI Thread, for example downloading a file from the internet, the user interface of your application will “freeze” until the corresponding task is finished. When this happens it is very easy for the user to perceive your application as slow.

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

  1. onPreExecute() – called on the UI thread before the thread starts running. This method is usually used to setup the task, for example by displaying a progress bar.

  2. doInBackground(Params…) – this is the method that runs on the background thread. In this method you should put all the code you want the application to perform in background. Referring to our Simple RSS Aplication, you would put here the code that downloads the XML feed and does the parsing. The doInBackground() is called immediately after onPreExecute(). When it finishes, it sends the result to the onPostExecute().

  3. onProgressUpdate() - called when you invoke publishProgress() in the doInBackground().

  4. onPostExecute(Result) – called on the UI thread after the background thread finishes. It takes as parameter the result received from doInBackground().

AsyncTask is a generic class, it uses 3 types: AsyncTask.

Params – the input. what you pass to the AsyncTask
Progress – if you have any updates, passed to onProgressUpdate()
Result – the output. what returns doInBackground()

Once a task is created, it can be executed like this:

new DownloadTast().execute(url1, url2, urln);

Here is one example of AsyncTask.

Solution 4:

Okay, without giving you the solution, I think it's best if you start reading up about asynchronous requests in Android: http://developer.android.com/reference/android/os/AsyncTask.html. Understanding the asynchronous nature of the web will help you appreciate the separation of your UI from the data that it might be rendering.

Responsiveness is the #1 reason you want to separate your UI from your data. This was probably best explained for Java Swing developers who used the EDT (Event Dispath Thread): http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html. There were so many examples of slow apps where developers would attach long-running processes to their buttons or whatever, and then try to fix it by using their own Threads to speed up processing. Swing eventually fixed this in Java 6 with SwingWorker and doInBackground(). For Swing developers coming over to Android, they'd probably look at AsyncTask and ask, why wasn't it that simple in Java?

So take some time to get familiar with AsyncTask, understand how to use it, how you could combine it with Listeners for even greater flexibility and then you'll understand how to change your code.

Let us know if you need any more help being pointed in the right direction.

Post a Comment for "Need More Understanding Of Asynctask In Android"