Search code examples
androidandroid-contentproviderandroid-cursorserializable

Making Android Cursor Serializable


I'm quite new to android and trying to implement a content provider using SQLite. The cursor returned from my query method has to be sent to another instance of app using a socket.

To send the data, I tried to encapsulate a cursor object within a serializable class which I'm then writing to my objectOutputStream which I later found will not work.

I've been reading about Parcelable which seems a bit complex and the only alternative I can think of is building a HashMap out of my cursor.

Is there any better way to this? Any help will be greatly appreciated.


Solution

  • If I had to do this, I would just loop through the cursor, read all the data, serialize it to JSON, write it to the socket, and call it a day.

    Now if you are one of those programmers with masochistic tendencies, I can offer an alternative. Consider that when you use a ContentProvider through a ContentResolver, the cursor data is serialized so it can move from one process to the other. The main class for this is the CursorWindow, which as it turns out is a Parcelable. As the app loops through the cursor, the driver for the cursor fills CursorWindows with data which get parceled and sent back to the app. You might be able to get that whole mechanism to work across a socket. You would have to do a little reverse engineering of the AbstractWindowedCursor class and all its friends to work out the details. For instance, there is a CrossProcessCursorWrapper class that might be helpful to you.

    However, be aware that you will be walking into a minefield. I've never had to get into the internals of data access through a service (i.e. across processes) so I have no idea of all the places where bugs could hide. Cursors are not required to be synchronized; the user of the Cursor has to take care of all the thread safety. SQLiteCursors have native resources and CursorWindow has some type of internal reference counting, so you would have to make sure you're doing all the right things at the right time so that nothing leaks. With apps on two different devices there may be UID/permissions issues.

    So I definitely think it's doable, but for me? I don't have the time to sort through all that stuff. I'll just stick to my caveman JSON code, thank you very much.