Why does the UI thread block when work is done on a separate thread?

In my application, I have a ViewPager with +/- 10 pages. When the application is open, all pages are created and immediately start loading data for display. Each page (which is fragments) creates an AsyncTask to query the database and populate it with the appropriate data. Here's the problem: even though the work is done in separate threads, the UI stops updating during database queries (which are sequential and take 1-3 seconds). This happens on both my Nexus 5 and black old Samsung phone, so I know the problem isn't that the hardware just can't keep up.

So ultimately I'm wondering why the UI thread is being blocked by work done on the background thread. My understanding of streaming was that working on one would not block the other for a long period of time. If my understanding is wrong, please explain how to do it. Thanks in advance.

I don't think the code is needed here, but if so, let me know and I'll post relevant snippets.

+3


source to share


1 answer


It stops animation right after the first database request and starts animation again right after the last database request completes

Perhaps then you are not doing work on a background thread that you think you are. You can do work on the main thread of the application.

Traceview can help you identify what you are doing on different threads, or it StrictMode

can help you with obvious problems (disk I / O and network I / O in the main thread of the application).



In this case, you may be caught in the way you are doing your job:

Each page (which is fragments) creates an AsyncTask to query the database and populate it with the appropriate data.

If you execute your query in doInBackground()

, but do not touch the resultant Cursor

also in doInBackground()

, the query has not actually completed yet. Cursor

is this SQLiteCursor

, and it lazy-executes the request when the data is first used. This is another one of those "really cool ideas that just suck in the way we're doing right now." A workaround is to call getCount()

on Cursor

while you are in doInBackground()

to make sure the request is running on a background thread.

+3


source







All Articles