1

I have an sqlite db with data I want to load async to a ListView. I know that Loaders enable easy async data fetching + getting notified on data changed, but from what I see, Loaders work with ContentProviders.

Since in the documentation, it says that

A content provider is only required if you need to share data between multiple applications

I find it weird that using Loaders require a ContentProvider.

I found this thread where it says in one of the answer's comments that

... taking this I just feel I should implement a content provider even so it seems like a overkill for any small database i might want to list on the display ...

Is this the recommended course on action? Is there an alternative?

Community
  • 1
  • 1
dors
  • 5,802
  • 8
  • 45
  • 71

1 Answers1

0

CursorLoader is designed to work with a content provider, but you can implement your custom Loader to work directly with the database, without implementing a content provider. take a look --> Android Custom Loader to Load Data Directly from SQLite Database

ILovemyPoncho
  • 2,762
  • 2
  • 24
  • 37
  • Hehe, I thought the Loaders were meant to make life easier... Will using the code from that tutorial trigger changes (insert,delete...) just as it would with ContentProviders? – dors Jun 06 '14 at 21:26
  • They do make life easier, `Loaders` keep track of the data source to deliver new results when data changes. And the `LoaderManager` takes care of configuration changes. e.g. comparing the regular `AsyncTask` and the loader version `AsyncTaskLoader`; with the first one, when the device orientation changes you have to handle it manually and you don't get updates, AsyncTaskLoader does all that for you. – ILovemyPoncho Jun 06 '14 at 21:37
  • OK, I gave the tutorial you suggested a shot. This works ok as long as I perform actions from my fragment who has my ListView, since I am able to use the same loader for CRUD actions. But in my case, I am able to add items to the DB from another fragment. In that fragment I don't have access to the Loader that belongs to my fragment with the ListView, and so I can't listen to those changes – dors Jun 13 '14 at 11:45
  • The LoaderManager ties loaders to the lifecycle of their creating components, in the tutorial it's the Fragment, since it uses `getLoaderManager.initLoader()`, this means the loader is stopped when you go to another fragment. Get the LoaderManager from the Activity instead: `getActivity().getLoaderManager().initLoader()` or `getActivity().getSupportLoaderManager().initLoader()` if you are using support library. This way the loaders are tied to the lifecycle of the Activity, and you will be able to share them between all fragments as long as they are displayed within the same activity. – ILovemyPoncho Jun 13 '14 at 20:15