I'm facing a serious problem in smooth scrolling of my table layout view. I've got some IO operations taking place in the service binded with an activity. The activity seems to have some lags in scrolling a table layout when the networking operations take place. I have no idea how can I agree the IO operations in another thread with scrolling the view. Of course I know how to sync threads, but the only thing which comes to my mind is to wait when the user starts scrolling, then make the IO thread to wait till it's over and continue IO after that. However I don't believe it's a perfect solutions because I've seen many apps in the android market that are able to scroll and query http simultanously.
Thanks in advance for any tips.
Have you tried using an AsyncTask for the network operations.
Related
AFAIK, android uses Single thread architecture, where all UI components event are dispatched,i.e. main thread or UI thread.
But why we cannot perform UI operations on separate thread other than main thread?
The main problem is related to the context. In a background thread you could update some UI stuff which is not in the current context. This is one of the reason.
UPDATE:
From the Android developer guide:
Additionally, the Andoid UI toolkit is not thread-safe. So, you must
not manipulate your UI from a worker thread—you must do all
manipulation to your user interface from the UI thread. Thus, there
are simply two rules to Android's single thread model:
Do not block the UI thread
Do not access the Android UI toolkit from outside the UI thread
You can read more on thread safety from [1] [2] and you can read even [3] with a small exmaple and explenation!
Hope that now it is more clear sorry for the short and quick answer before :)
Well, first of all I need to state that this is a design level problem that has been discussed by many generations of programmers :)
Now technical details:
A GUI framework is a very complex thing. A GUI framework needs to display (draw) certain views (or windows) and route external (mostly user) inputs to the view that the input is targeted to. Now, to manage the screen with views with proper event dispatch to each view, all views shall be part of a graph and the simplest form of such a graph is a tree. So, you essentially have a tree of views to manage - where information should be fed to a root view from where your whole event routing takes place to child views.
Naturally, one dedicated thread to do manage this view hierarchy and event routing by monitoring a message queue to which all these drawing and input events are posted - by itself or any other threads - is a neat and simple solution. Any other solution that involves more than a thread will make the already complex view management and event routing code prone to dead/live locks.
Along with these technical details, you need to keep it in mind that you are trying to do business with a framework which is going to be used by other people who usually don't have faintest idea about the inner details of your architecture. Introduce threading support in such a framework is an open invitation for synchronization bugs (read: deadlocks, grumpy end users who are programmers AND ultimately bad business).
Android (and 99% other GUI toolkits) adopts this method. Simply because it makes things simpler and less error prone to have one main thread to deal with all error prone processing. All other threads are free to request it to do things by posting messages to the main thread's message queue. It is a balance between complexity and stability.
The only drawback of this approach is smooth updates of views - if you have many views to update simultaneously, OR your view hierarchy itself is really nested and complex. This drawback of this single threaded architecture manifest itself in pretty obvious forms in Android like:
Animating multiple views simultaneously is never smooth - unlike iOS where they have taken the pains to move certain parts of this operation to more than one threads of execution.
Android documentation need to remind the programmer all the time not to do lengthy operations in main thread AND to avoid deeply nested view hierarchies.
I am working on an application that Looks similar to the Google Play App (swipe view with gridviews inside the fragments, in addition data in the gridview [image + text] is retrieved from a remote server).
My problem is with background tasks. I can’t decide what to use for retrieval of data from the internet. Mainly I am trying to decide whether to use AsyncTask or manual threading.
Of course it would be easier to implement AsyncTask, but after some research I noticed that many people find it limiting.
In my particular case, I want to download data from the internet as Json Objects, parse them and display the data in the gridview. The gridview would have up to 30 items, each item contains a thumbnail and 3 textviews. In Android documentation, they say that AsyncTask is suitable for short operations (few seconds at most). Would filling up to 30 items be considered as a short operation?
I want the data to be fetched concurrently. Also I want to support Android phones from API 8 and above. I read that for different APIs AsyncTask behaves differently (serially or concurrently)
My question is: Is it appropriate to use AsyncTask for my app? Or do I have to do everything manually? Is ThreadPoolExecutor a 3rd way to do this? Is it easier than manual threading?
Any advice would be appreciated, I can't move forward in the implementation without deciding on this issue.
Thanks in Advance!
My understanding is that the comment about using AsyncTasks only for short operations is aimed more at not expecting the same views to be available when a long operation finishes. For example, if a user leaves the app and comes back or the current activity goes away for some reason. Typical ways around this would be to use a Service and start up a plain old Thread there, then send some message telling the current Activity to refresh when the operation is done.
The download and processing of your data is likely to be the longest operation. So I'd use that as a basis for whether this is short or long. If you don't care about persisting data at all and don't mind restarting downloads if a user leaves and comes back, you can just use an AsyncTask with very little thought.
If you are using a GridView, you should only ever be populating enough views to for just over the number displayed on the screen at one time.
I'd say that AsyncTask is fine in your situation assuming it's a few kilobytes of data and not megabytes or hundreds of kilobytes. Megs of data, I'd say move to a Service with a Thread. Hundreds of k, is a toss up.
Also, take a look into Loaders... if you want to see an alternative that is better for this kind of loading.
When attending DroidCon in London last year, a presentation brought to my attention why using AsyncTasks for loading data from the network is unreliable.
This presentation was about the RoboSpice library.
The site also has a very nice infographic explaining why exactly AsyncTasks are unreliable and what RoboSpice does to amend these problems.
Disclaimer:
I am in no way affiliated with RoboSpice, nor have I ever tried it. I was just impressed and convinced by their presentation that it's a tool worth trying.
Friend, I am working in a project exactly as you need, and to support API 8 and above you should use Asynctask to download anything or you will get a crash for API 15 and above, because it won't even let you run your app without AsyncTask even for short operations.
So as I almost did everything that you need and it is working very well for API 9 above, you should use Asynctask, I´ve implemented SherlockActionbar, EndlessAdapter and ViewPager all with AsyncTask, so go on, if you need more help just ask again later.
I have a listview in parent activity and I am passing some parameter from parent screen to child activity.Also I have custom theme and title bar.My question is When I go from parent listview to child view screen, it takes too long time and black screen comes for a while.
What is the reason and how can I avoid it?
I searched in google a bit and also I saw one reason but it did not work for me.
Can anybody help me?
From the description you have a processing problem, not a display problem. You need to identify the routine that is taking too long to complete. Without seeing the processing code it is difficult to recommend a solution.
Here are a few things may help:
Are you running the app on a real device or using the emulator? - The emulator is notoriously slow. Try running it on a real device.
Are you accessing an on-line resource like a web site or web service on the UI thread? All on-line accesses should be run on a dedicated thread.
Where is your processing being done? Do not do excess processing in the onClick of the ListView because it will be run on the UI thread. Place only MINIMAL processing in the onCreate method in the new Activity because this is also run on the UI thread. The best place to put lengthy processing is in the onResume method of the new Activity (this is still run on the UI thread) and ideally pass off the processing to another thread.
Are you accessing a local SQLite database? If so, your SQL statements and/or database may not be optimized for performance. If you are using a local database and are not a strong SQL programmer, ask someone to look at your statements or post them here.
Does your app use a large amount of memory such as large arrays or images loaded into memory? If so, reduce the memory requirements - only hold in memory what you must have at any moment.
If none of these help, please post a detailed description of the processing you do between the onClick of the ListView through to the point where you are ready for another user input.
When you reach to next screen please put your processing task in thread (in OnCreate()) and show progress dialog for waiting.
Edit - Try with this theme in activity and let me know what happend.
#android:style/Theme.Translucent.NoTitleBar
I’ve been working on building a nice graphical selector for an Android project. Unfortunately, this selector is causing me lots of frustration due to a deadlock in the application’s UI thread. Parsing and rendering the various SVG layers that make up each clock is a relatively expensive operation. Locking up the user interface while doing these operations is clearly bad design, so I'm trying hard to give good feedback.
The selector consists of two columns, an image of the clock on the left and the name of the clock on the right. Using the standard ListActivity support, the goal is to show an indeterminate progress image in the left column until the clock layers have been loaded and rendered. At that point, the animated progress image is hidden and the clock image is displayed.
The implementation is simple in concept. The list adapter subclasses the standard BaseAdapter implementation to provide an implementation of the getView method. The getView method delegates loading of the clock’s image to an asynchronous executor service, keeping the user interface alive. When the asynchronous task completes, it posts a runnable to the UI thread to hide the progress indicator and show the image view. There is logic related to properly handling recycled item views as well.
While this is mostly working, I’m hitting a random deadlock condition that locks up the UI thread, usually resulting in an “Application Not Responding” (ANR) error message to the user. All of my attempts to diagnose and resolve this issue have ended with nothing but frustration. So far, I’ve tried all of the “standard” approaches to diagnose this:
Analyzed the traces.txt file generated by the ANR.
Unfortunately, the process never shows up in the log file.
Force-generated a traces.txt file using kill SIGQUIT pid while the application was still running. Again, the process doesn’t seem to show up. Instead, I see “W/dalvikvm(19144): threadid=4: spin on suspend #1 threadid=9 (pcf=0)” whenever attempting this.
Enabled kernel-level deadlock prediction, but it never showed anything
Attempted to use the standard Eclipse debugger to suspend the UI thread once it is locked up.
No big surprise that it did not work. Added lots of Log output trying to pinpoint the hang. At least from that logging, it doesn’t appear to be a hang anywhere directly in my code.
I even tried to use method tracing to see if I could figure anything out.
At this point, I’ve run out of good ideas on how to track down and fix this problem on my own. I've removed all synchronization in my code and I'm still hanging up, implying some kind of hang in the underlying platform code. Without a stack trace, I'm truly flying blind at this point. Can anyone offer any ideas?
writing a small android game for a university assignment and just wanted to check what I'm doing is correct.
I'm creating a Mastermind type game and am unsure how to handle basic game operations such as checking if a guess is correct.
Am I correct in thinking that the best way to handle these operations is to create inner classes that extend Async to avoid UI lockup?
If not could anyone suggest any other ways?
Cheers!
After many weeks of developing my application, AsyncTask is what I used instead of standard threads. AyncTasks are less likely to get killed, they create a worker thread and handlers by themselves so you can update GUI through it more easily than standard threads. But remember that only one instance of AsyncTask can work at a time.
I don't think you need AsyncTask for this game at all. AsyncTask is a process for which you do not know how long it will take and you don't want to block your UI thread, like downloading something from Internet.
Your game can be completly events driven. Whenever the user makes a move you call your methods.
If you want to have animations while the user thinks then SurfaceView can do the job.