In my Android app, I am making a http request, getting some data, putting it in my local sqlite database & then populating a gridview using that data. I have the code working for an activity but I need to use fragment now to get this done as there are many similar pages to be shown. I read that using Loader is the best way to deal with data in a fragment.
I am not sure about:
- Whether to use CursorLoader, Async taskLoader or SQLiteLoader(developed by commons guy).
- In which of the loader functions (onCreateLoader(), onLoadFinished() etc.) do I put my code for making http request, populating the local database & getting the data displayed in a gridview in my fragment
- I am also using a lazyload list to show images. How will that fit into the entire thing if I use loader
Can anybody help me with this one? Tried searching for good examples or tutorials but I haven’t really found something that’s really useful. So, please suggest any if you can. Thanks
CursorLoaderis forContentProviders(which is not your case) andAsyncTaskLoaderis the way to go. I haven’t use the classes from Commonsware but if they allow overriding of some of their methods then I guess you can use it.In none of those callbacks because they run(most likely) on the main UI and you must not do network operations in there. The
Loadersubclasses have theloadInBackgroundmethod which runs on a background thread. On this method theLoaderqueries for data and in which you could place your networks requests and database updating. But you would need to be very careful to not insert duplicate data in the database.As I haven’t seen your code, I don’t think this two parts are connected. I’m guessing that you use the lazy image loading code directly in the
GridView‘s adapter.My advice is to not use Loaders for loading and inserting data because their purpose is to only load data on a background thread(having taking care of configuration changes). For your particular situation I would make my own
AsyncTaskLoader(or use Commonsware’s library) which queries the database for new data. I would then start a newAsyncTaskto do the http request and to insert data in the database and then I would trigger aLoaderrestart in theonPostExecutemethod of theAsyncTask(withgetLoaderManager().restartLoader...). Have a look at this similar question for some problems related to what you’re trying to do.