I've an Android application that connects to a server api (CRUD) to manage a model. The app needs to work offline, therefore the app has a database that stores the data pulled from the server.
The instances of the model have an attribute named ID which is created in the server.
In order to perform a create offline operation I a difficult problem. As there is no connection I need to store the entity to the database, however it does not have an id yet. Which is the best - general solution to do this?
Should I add a second attribute in the database that will be the "temporal id" (for example using an UID)? Maybe I don't add this data to the database but to a temporal queue? What happens with the relationships with this entity?
You always will need a local id for your rows, used as primary key (the could be incremental, that will make things easier). After that anytime you sync with your server you will have a remote id aswell, this remote id will be used to link your local row with a remote row in your server.
So,
-when you get a row from the server, make sure you fill your remote id and let SQLite to fill the local id,
-when you create a row from the mobile (or all the entries in your database without remote key), send it using your local id (which will be ignored from the server) and then assign a new remote id from the server. Finally your server should return the new rows with the remote id field filled, making the whole cycle.
Hope it helps
EDIT:
In order to make this work, your mobile and your server tables will be slightly different. In your server you will have a local id, this local id will have to match your remote id in your mobile.
If you get fom the server a row you will need to check if you have the remote id (that is your linker field). If you do not have any rows with that remote id, you will be inserting new rows, otherwise you will be updating them.
There is only one more thing to complete this process, when you send a row to the server you will need an extra field (in your json or your xml) which will tell you that your row is yours.
Exists only one case in which you will receive a mobile local id from the server, and it is when you upload new rows.
In this case you will receive your mobile local id, and the remote id. Now you will be able to link the local information with the remote one.
Summarising:
When you get new rows from the server, you will receive only mobile remote id (server local id), use this remote id, to check if you have to update or insert.
When you send rows to the server, the server will return you the local mobile id and the remote mobile id, this way, you will know that the received rows are yours. In this case, you will have to update your local rows to store the remote mobile id.
The server will never store local mobile ids as it makes no sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With