Asynchronously load data in android - android

what is meant by asynchronously loading data in activity or fragment in android?
This is my question. I searched everywhere. I'm not getting a generalized definition for this?. I can't get the term mentioned in android developer also.
Can anyone provide me the basic explanation of this term?

Asynchronous in Android mean that you do stuff while the user can interact with the User Interface (UI) : you are not blocking the UI while you are doing long stuff. So the user can still navigate, change activities or fragment and your data is still loading.
For data : you load it, parse it and do whatever you want in a NON-UI Thread (using AsyncTask eg) and then notify the UI, and display what you need to.
You have many possibilities to implement Asynchronous load in Android, and you have many different way to manage your request. I personnaly recommend using Retrofit if you need to use a Web API.

It means that you load your data in a separate thread than the UI thread. You launch your HTTP request for example in another thread and when it finished you notify the UI thread to refresh display.

This mean to load data in separate thread rather than load the data in main thread.Loading data in main thread may cause app to block

The AsyncTask class encapsulates the creation of a background process and the synchronization with the main thread. It also supports reporting progress of the running tasks.
To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask .
An AsyncTask is started via the execute() method.
The execute() method calls the doInBackground() and the onPostExecute() method.
TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method and is passed to onPostExecute() as a parameter.
The doInBackground() method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate Thread.
The onPostExecute() method synchronizes itself again with the user interface thread and allows it to be updated. This method is called by the framework once the doInBackground() method finishes.

Related

Android studio AsyncTask

I am using sockets and im getting data continuously in background using Asynctask.
I send this data to onProgressUpdate() with publishProgress()and I would like to know if there is a way to get the data from function onProgressUpdate() or send it to another class, because where I do need to use this data is in another class. At least, is this possible?
I have a .java, in this .java I have 2 public classes:
First one is a class where I use this Asynctask in background to get socket info.
In the second public class I use OpenGL and I need to use that data.
Thank you
Sure it's possible. You define the type of the array passed between doInBackground() and onProgressUpdate(). You can just publish the progress and consume it that way.
new AsyncTask<...,MyDataObject,...>() {...}.execute();
Alternatively, you can create a publish-subscribe interface between the thread running dIB() and whatever thread is consuming it.
Not that AsyncTask isn't intended to be used for long-running operations. It's meant to be a relatively quick one-shot. You'll need to consider running your task on a dedicated executor so as not to block the one serial executor that's used by default for all other instances of AsyncTask. E.g.,
executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Yo can do this with publishProgress() method and you can call this method from doInBackground() and this method can be called at any time when you need to get your data.
Then get data what you want from params and store it in public variable of Asynctask and access it from another class.
This may be work.

Generic AsyncTask with Error Handling and progress dialog

please tell me best way to write this.
I need one generic AsyncTask for webservice call with all possible errror handling. Also a callback for updating UI/ showing error message.
I have found few approches :
by adding Generic parameter to async task
making asynctask as abstract
for handling error giving handler object.
This is actually very easy to do with an AsyncTask.
AsyncTask has 4 functions. 3 of them run on the UI Thread so you can update the UI as much as you like. 1 of the functions runs in the background so you can do things that take as long as is necessary, such as calling your webservice.
You do not need a formal callback function. AsyncTask.onPostExecute() handles this for you.
There is a great example in the Android documentation that shows how to download a file exactly as you are trying to do with the webservices connection. You will extend AsyncTask and create your own DownloadFilesTask just like in the example.
The whole thing is started with a single line of code:
new DownloadFilesTask().execute(...)
The four functions are:
onPreExecute() - Useful for displaying a ProgressBar or other
UI elements.
doInBackground() - Take as long as you want, but don't update
the UI from here. Instead, call publishProgress() as often as you
like. That will internally call onProgressUpdate() where you can
incrementally update the UI, or your ProgressBar, if you want.
onProgressUpdate() - Optional show progress updates or increment
a ProgressBar. This function only gets called in response to calling
publishProgress() from doInBackground().
onPostExecute() - Done, dismiss() your ProgressBar, update
the UI, process any errors saved in doInBackground(), and jump to
the next section of your code.
Error Handling:
All errors are trapped in doInBackground(). You should save an int errorCode and/or String errorMessage in your DownloadFilesTask class, and return; from doInBackground() when an error occurs. Then, process and report the error in onPostExecute().
See this question for several answers. They all involve storing any exception thrown by doInBackground in a field and checking it in onPostExecute. I like this answer posted by #dongshengcn, which encapsulates this into a subclass of AsyncTask, then you can override onResult and/or onException as necessary.

One difference between handler and AsyncTask in Android

Why can an AsyncTask perform only one job? For example,
task = new SubAsyncTask(...); // assume the parameter is correct.
task.execute(...) //
task.execute(...)// calling once again, it throws exeception.
But a Handler can continously perform more than one task:
hd = new Handler(...); // assume the parameter is correct
hd.sendMessage(...); //
hd.sendMessage(...);// no exeception is thrown.
Is an AasyncTask object for a one-time job only? If I don't want to create multiple object for similar task, should I choose Handler?
Handler and AsyncTasks are way to implement multithreading with UI/Event Thread.
Handler allows to add messages to the thread which creates it and It also enables you to schedule some runnable to execute at some time in future.
Async task enables you to implement MultiThreading without get Hands dirty into threads. Async Task provides some methods which need to be defined to get your code works. in onPreExecute you can define code, which need to be executed before background processing starts. doInBackground have code which needs to be executed in background, in doInBackground we can send results to multiple times to event thread by publishProgress() method, to notify background processing has been completed we can return results simply. onProgressUpdate() method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update event thread, onPostExecute() method handles results returned by doInBackground method.
So, you dont need to call execute method on AsyncTask multiple TImes, instead you can invoke publishProgress.
Because that is how the class was designed. The idea is: do something with UI (show progress dialog, etc.), do work on background thread and return results, update UI. The Handler is fundamentally different: it lets you post messages, but it does not create a background thread for you. If you don't like how AsyncTask works, build something similar by using threads/executors and handlers.

AsyncTask - How to wait for onPostExecute() to complete before using values it has updated

I have an API in one jar that uses AsyncTask to carry out some work in the background. I need to wait for the result to be returned and then do some more wok with this result.
I signal back to one class in onPostExecute() method and then the result is handled on the UI thread, but the handler needs to be defined as a callback in a different project altogether so I can't just do the work in the onPostExecute.
In the second project I need to wait for the AsyncTask to end AND for the response to be handled, then I need to display the results of the handler to a TextView in an activity in the second project.
Thread.sleep and using a CountDownLatch don't work because the handling is done in the UI thread. Is there any way to do such a thing?
If I understand correctly, you have AsyncTask in one jar and UI that needs to be updated in another jar. If you run them as one application it should not matter where they are located. Since you mentioned that some callback is involved you can just execute this callback in onPostExecute.
The following will be an approximate sequence of events
Activity from jar 2 creates async task and passes callback that knows how to update TextView as parameter to constructor
AsyncTask stores callback in instance variable
Activity executes AsyncTask
AsyncTask in onPostExecute calls method on callback with appropriate parameters
Callback updates TextView

What is the need of Asynchronous Task

We have to use Asynchronous Task to start our new Activity on Tab Click event but in the ListView or any view we can directly can start the new activity Why?
http://developer.android.com/reference/android/os/AsyncTask.html
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.
An asynchronous task is defined by a
computation that runs on a background
thread and whose result is published
on the UI thread.on the UI thread.
Basically you want to avoid that the loading process/device hangs when loading loads of data to the list initially, that's why you make it async, outside the UI thread, so the user can use the app while data is loading in the background.
Starting an activity is faster than loading lots of initial data into a long list view, especially if it's remote data from a remote server. Therefore the app you're looking at is probably using this here.
If you want to perform some task in background at the same time you want to do another task at the forground.
http://developer.android.com/reference/android/os/AsyncTask.html
This link surely will help you.
You just try this one will help you.
http://xoriant.com/blog/mobile-application-development/android-async-task.html

Categories

Resources