Reputation: 12194
I need to build an android app that handles files in the /sdcard
directory. For each file, I want to give functionalities like tagging a file. I believe to use local DB to handle this.
The problem is that if a user renames the file I lose the tags because they are related to the previous filename.
Is there a way to avoid this problem, like for example set/get a unique identifier for a file that does not change even when the file is renamed ?
Upvotes: 2
Views: 276
Reputation: 1451
What you need is a unique ID for each file in your database, and to link all of your tags with that ID instead of the filename (it can generated however you like, an integer or a hash or random numbers will be all fine, all that matters is that no other file has the same ID otherwise the tags will be shown for both files).
In your database you can keep one table which links the names of the files to the ID (or, more flexibly, link the IDs with the paths to the files and extract the names from that when you need them). When you add a tag, link it to that ID like you would the filename. It costs you a trivial ID database lookup when you load a file's tags, but allows you to rename your files in one place (rather than having to walk through the database looking for the filename).
To catch people renaming your files, you can create a FileObserver to watch for MOVE_SELF events (which would be renames - a rename is the same as a move). You can override the FileObserver.onEvent() method, where you can update your database with the new name of the file. You'll want to do this in a separate thread, to avoid locking up the UI. It also won't persist after your activity, so you would want to either have a Service to hold the FileObserver and update your database, or just have some kind of scan happening when your Activity is launched.
Upvotes: 3