Inserting records via Loaders in android

后端 未结 1 1693
悲哀的现实
悲哀的现实 2021-01-21 13:30

This question would be a follow up from the one asked Content Resolver vs Cursor Loader Where the answer clearly states how to insert records into a sqlite Db using a Content Re

1条回答
  •  终归单人心
    2021-01-21 14:07

    Can i use a loader(Normal Loader) to implement this functionality ?

    You can't use a default CursorLoader to insert data. If you implement your own Loader you could probably use the loadInBackground method to do the insert but that will make your code awkward at best(and I don't know if it will actually work).

    Would this run the functionality in the Main UI thread or a worker Thread . I understand that i would not receive callbacks for this as the content resolver will return a URI instead of the cursor containing data .

    The loader callbacks will run on the thread where they are implemented(the UI main thread most likely) so you're doing the getContentResolver().insert() on the main UI thread with the possibility of blocking the main UI thread.

    I tried running this code but it behaves kind of wierd .. Duplicate inserts are recorded and its not consistient ,

    Have you tested how many times is the onCreateLoader method called?

    Could someone show me to some right resource which uses a Loader to do Insert operations ( I have seen many examples with query examples and it works like a charm :) )

    Don't use/try to use a Loader to insert data in the ContentProvider/Database. It works like a charm for queries because the loaders were designed to load data from a data source(not insert data), that is their purpose. If you want to insert data use an AsyncTask(also have a look at AsyncQueryhandler), a regular thread.

    0 讨论(0)
提交回复
热议问题