i have an application in which i have a UI activity which is supposed to display data which is retrieved after xml parsing done in another class.
during the xml parsing what i am doing is showing a progressdialog. i pass the handler of my ui activity to the thread doing xml parsing and when parsing is done , the xmlparser therad, using the handler that i have passed dispatches a message which is received by the UI activity after which it starts displaying the data.
the above is how i am doing multithreading.
is there a better way to do the same?
thank you in advance.
Edit: i have heard of the following async task, executionarservice, intent service.
which is the best for my purpose?
AsyncTask is your best friend if you are doing mutlithreading in android.
Instead of passing runnables to the UI THread, you need to implement a AsyncTask class, and them inside have it parse the xml in doInBackground().
For the progress dialog, initiate the dialog and the show it when onPreExecute() and dismiss it with onPostExecute(). If you want a precentage bar you can implement that in onProgressUpdate()
Surely there are several techniques for this task.
You can achieve multithreading by using Services, AsyncTasks, Handlers, ...
For taking the right decision based on your problem, i suggest you to take a look at Romain Guy's Painless Threading post on Android Developers. This is a very handy article, and very precise as well, never gets old.
Related
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.
I'm developing an Android app that has a basic structure: activity that requests some action from AsyncTask implementer. The implementer has 3 custom methods that should be able to update UI thread with a Dialog and a postExecute() that should update UI thread with a failuer Dialog if an exception is thrown. Here are some questions:
Where should I create the Dialog object? In the activity class or the AsyncTask implementer? What general guidelines should I follow?
Can I update UI thread with a Dialog without waiting for postExecute()?
How can I update UI thread with a picture? Should I create a custom Dialog or is there an easier way?
If the updates - as dialogs with pictures - come one after another, in a sequence how should I deal with it? Should I create some kind of queue? How would you do it?
Thank you in advance :)
1)There's a couple of different ways you can do this. But personally I usually create the dialog in onPreExecute of the AsyncTask, so that the UI for the task is completely self contained.
2)Yes. You can do it in onProgressUpdate. doInBackground should call publishProgress() which will cause onProgressUpdate to be called on the UI thread.
3)Too few details- where do you want the picture? In an existing image view? On top of the current layout? If you just want to display it in a dialog box, an AlertDialog with custom layout would probably work.
4)Depends on the app. Do you want the user to see all the images, or is it ok to miss images in the middle if a new one is sent?
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.
I need some suggestion on how to go about this specific android problem:
activity A passes an intent to activity B,
B reads it, makes an API call,
B receives response, parses it, and updates its views from the response
now it works fine except fr a 2 second black screen during transition from A to B
is asynctask a solution? becoz the parsing data is not much and also is there a way to update UI views frm asynctask
To echo what Lalit said, an AsyncTask will help in this case. The problem that you're having is that doing the API call during onCreate is blocking the activity from updating the UI. If you use an AsyncTask, it will allow the activity to continue rendering the view.
As you're parsing the result, you can update the UI by calling Activity.runOnUiThread() or by putting the UI code in onPostExecute.
I'm not sure if AsyncTask is the best solution for your case.
An AsyncTask is very helpful if you need to do something in background and allow the user to do something else in the mean time.
I'd sugest to just use a Thread and define a progressDialog.
If you do it this way, your user will see the loading dialog with the spinning circe and not the black screen that looks more like if the App is freezing.
Let me know if you need help with some code samples.
Marco :)
Hello
I have ListView with list of files. i click item and start to download this file in asynctask.
then i click another one and it must be put in queue, wait for that file and start ot download after it finishes. i can make some class that will hold all clicked links, and pass it to asynctask downloading part? and than somehow process them. but want to know is it the right way?
any links of sugestions? thanks
If you're set on using AsyncTask then, yeah, hold your clicked links and kick off new tasks when appropriate. You should note that AsyncTask is like the 'pocket knife' for threading in Android apps.
If you really need to manage a bunch of background tasks, and it sounds like you do, take a look at ThreadPoolExecutor. You get a lot of flexibility.
BlockingQueue
ThreadPoolExecutor
More Info
Example
Take a look at HandlerThread and the Handler class. You need one handler to pass tasks to the background HandlerThread and another for the UI thread to pass results back to the UI
Even though old, got here from Google: consider an IntentService.