I am connecting to a web service using
urlConnection.connect();
This works only in AsyncTask. I am not able to execute the above statement on plain activity (without AsyncTask )
Is it the behavior by design, or I am missing something.
By the way, this is my first question
Welcome to stackoverflow. please use google search and stackoverflow search before posting a question. the chnaces are big, that someone else had already asked your question. stackoverflow rules
Network communications must be done in seprate Thread in android.
Read more about it here developer wiki
To avoid creating an unresponsive UI, don't perform network operations on the UI thread.
You are possibly getting:
NetworkOnMainThreadException
because you are trying to perform network operation on Main UI Thread and thus overwhelming it. Instead use an AsyncTask.
Also, note that if the server is taking much time to respond, the main thread becomes unresponsive too.
Refer Android Doc for Developers for more information on this.
Related
I'm currently writing and android app, and I was using HttpClients and those classes. I spent 2 hours trying to fix some errors until I read a post that said that you cant do that operation in the main thread. So they suggested I use AsyncTask.
So My question is, how do I know which operations should be done in a different Thread? is there a list where I can read them?
Any information would be good, thanks in advance.
A NetworkOnMainThreadException is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.
Some examples of other operations that ICS and HoneyComb won't allow you to perform on the UI thread are:
Opening a Socket connection (i.e. new Socket()).
HTTP requests (i.e. HTTPClient and HTTPUrlConnection).
Attempting to connect to a remote MySQL database.
Downloading a file (i.e. Downloader.downloadFile()).
If you are attempting to perform any of these operations on the UI thread, you must wrap them in a worker thread. The easiest way to do this is to use of an AsyncTask, which allows you to perform asynchronous work on your user interface. An AsyncTask will perform the blocking operations in a worker thread and will publish the results on the UI thread, without requiring you to handle threads and/or handlers yourself.
The network exception is the only exception that will be thrown in android by blocking the UI-Thread. So you have to keep 3 rules in mind by programming in android.
Don't let the UI-Thread handle operations that will take more then 5 seconds to complete.
Don't let a broadcast receiver handle operations that will take more then 20 seconds to complete the onReceive ().
And don't handle network operations in the UI-Thread.
As other answers have said, Android is not thread safe, meaning:
You cannot manipulate the UI from a Background thread
You cannot do heavy tasks on the UI thread
Other operations of this sort could include processing large amounts of data/ database manipulation/HTTP requests/Network management. Really, I believe anything that doesn't require the UI thread but does involve large processing time should be moved to a seperate thread.
This makes logical sense, because if you were to do heavy processing, the user would feel a lag and User Experience would be compromised (and, ofcourse, could definitely be used to overload the system,etc.) Therefore, the system will kill the process and throw an error post-honeycomb.
As a result, you want to use an Async Task.
An Async Task really just opens a new Thread on which you can execute heavy processing or Network Connections. For Network Connections, I recommend the use of AsyncClients like this one that implement AsyncTask in an easier format for you to use. There are also libraries like UniversalImageLoader that will allow you to load Images into Grids/Lists.
I also highly reccomend you read the official Android documentation discussing this and there is a useful post on the Android blog about this as well. Lastly, I feel as if this post might be useful to you because it may include the error you encountered (Error because you performed the operation on the UI thread).
Other Resources I've found:
CommonsWare's Service
This StackOverflow Question has some good solutions.
In conclusion, here is an example of an AsyncTask being used. (nicely put answer from #Graham Smith).
Anything that takes a lot of time should be done in another thread. This includes large IO and network access. However I think only network access will throw an exception, anything else would cause an unresponsive UI. Although if you take way too long you'll trip a watchdog timer and the app will be killed.
As Gabe mentioned, you should do heavy tasks in separate threads.
there are two important things about android threads.
1 is the common threads..(the thread that do what you ask)
2 is the ui thread...(the thread that listens the user inreaction and draws ui)
you can change ui(Views act) only by ui thread.
on the other hand after honeycomb it is forbidden to do http requests in main thread.
(it is called strict mode)
in short, any operation that blocks user interaction should be done in another thread.
i hope this helps you.
Im trying to connect to a SOAP service using Android and have read in SO as well as other websites about using ksoap2.
Ive also been reading Android in Action, which indicates that any long running code (> 5 seconds) in a UI thread should be done in either a Handler or as a Service. Are there any recommendations on when to use these as opposed to just using it inside the Activity. Many examples in SO as well as on the internet do SOAP processing right inside the Activity (either in the lifecycle methods or on event handlers) but in my case, I know that there are certain SOAP methods that are going to take more than 5 seconds.
Any pointers or recommendations of when to use Android Handler or Services would be very helpful.
If the UI is depending on the response in that same instance of time, then I recommend you to make use of AsyncTask class. AsyncTask are designed and recommended for such long operations. As an assumption that response of the server is strongly related to the UI than you MUST NOT keep the UI frozen while that long operation is in progress.
You can do these long transactions in the doInBackground() method which will run on background thread, must note that in this method YOU CAN'T UPDATE THE UI, and in onPostExecute()/onProgressUpdate() you update the UI with the response from the server.
Read more on AsynTask if you haven't been introduced alread, here:
http://developer.android.com/reference/android/os/AsyncTask.html
Don't forget to mind the Threading Rules
I recommend using AsyncTask instead. Look it up here: http://developer.android.com/reference/android/os/AsyncTask.html
Basically, you can execute your SOAP calls in doInBackgroundmethod, which is executed in a background thread, and you can update your UI in onPostExecute() method, that way you can avoid the dreaded ANR (Android Not Responding) error.
Have a look at this for an example of AsyncTask.
I suggest you refer the Android Developers page for AsyncTask properly before you begin implementation.
All the best
Cheers
I have an application that makes a lot of network requests for xml data that is parsed and presented to the user. Best practices dictate to relegate the network request code and parsing to another thread but since the UI elements have thread affinity it's hard to get the information onto the main thread to be displayed. Does anyone know of any good resources for android threading?
I like to use the Handler class. When you post or sendMessage with it, it will always execute its command on the thread it was created in.
This Android Developers blog post covers a couple techniques:
Painless Threading: http://android-developers.blogspot.ro/2009/05/painless-threading.html
Have you seen this google.io talk about consuming services?
http://www.youtube.com/watch?v=xHXn3Kg2IQE
Can anyone give me a clear description of what is AsyncCallBack? Does it exist in the latest android version? Because I am directed to AsyncTask when I search for AsyncCallBack.... Are these both same? Does anyone have an example?
Thanks in advance.
There is no class named AsyncCallback in android. I think what you are looking for is AsyncTask which is a way to run a piece of code on another Thread so the UI won't be blocked, and receive it's results on the UI thread. For example, say you want to talk to a server on the internet in response to the user clicking something in the UI, then receive some result from the server, and update the UI. AsyncTask makes doing this very easy compared to doing regular threading code because threading lifecycle and communication back to the UI thread is handled for you. As a bonus there is also support for canceling a background task, but you have to write the code to handle it when cancel is called. It doesn't do it without some work on your side.
I think the terms may be mixed up here, there isn't an AsyncCallback in Android (as far as I know). There is however very widely used AsyncCallback interface in GWT (Google Web Toolkit): http://google-web-toolkit.googlecode.com/svn/javadoc/2.1/com/google/gwt/user/client/rpc/AsyncCallback.html.
In Android you use AsyncTask to easily run background operations asynchronously on a separate Thread from the main UI/app thread: http://developer.android.com/reference/android/os/AsyncTask.html.
Here is a good intro article on AsyncTask: http://developer.android.com/resources/articles/painless-threading.html.
Can anybody tell about the "asynctask" used in android application. Currently I am working on an application where I have to create a Class in which I have to just get the response of any particular URL given.
I this particular class I was told to perform this task by making use of "asynctask". I had been getting very quick responses of all my Questions from here so far and I am greatly obliged to all of them who are helping me since my first question I posted here.
I am quite new to Android Programming and feeling a bit confidence by the community's camouflage with me.
Thanks,
david
Google's documentation for AsyncTask is pretty excellent: http://developer.android.com/reference/android/os/AsyncTask.html
It's basically a construct that makes threading very simple. When you are doing something like making a web request to some URL, you don't want to block the UI thread. However, you usually want to update your UI with the results once your background task has completed.
AsyncTask makes this easy. First, you need to create a class that extends AsyncTask. When you execute the task, its doInBackground method will be called on a background thread. This is where you can download something from the Web or do whatever else you need to do.
The return value from doInBackgroundwill be provided to the onPostExecute method, which can update the UI appropriately.
Again, I recommend checking out Google's documentation. They've got great examples on how to use this.