Reputation: 443
I was developing an Android Application where I have to load a large data from Android Database and view it on screen.
In earlier stages of development I used to retrieve data from DB in OnCreate() method and it really slowed the start of activity when data became huge. So I called the retrieving of data and viewing it on screen in OnResume() method, so that my app does not crash while taking too long to load it. I know activity is not shown until OnResume is completed.
So is it a good approach to call time taking operations in OnResume instead of having all initialization in OnCreate() method?
Upvotes: 4
Views: 1107
Reputation: 34532
You should never do IO operations on the main thread. This includes onCreate
and onResume
methods, which will always be called on the main thread.
To correctly load data you should either use an AsyncTask or the ContentLoader with its callbacks.
Generally speaking, to use a database with your application you should use a ContentProvider
and CursorLoader
s. There are plenty of tutorials on how to use these and it makes your code better manageable.
Upvotes: 1
Reputation: 49986
So is it a good approach to call time taking operations in OnResume instead of having all initialization in OnCreate() method?
no - you should not do it inside OnCreate or OnResume. You should always do it inside working thread - like AsyncTask.
Any opertion that takes to long to finish, if executed on UI thread will block message queue - this means there are no repaint of UI widgets, user cannot tap on your app to do anything. Everything is blocked until your operation finished. After ~5s Android generates ANR (application is not responding) and kills your app.
Upvotes: 3