static String generateFilenameForKey ( SQLDatabase db , String keyString ) throws NameGenerationException { String filename = null ; long result = - 1 ; // -1 is error for insert call int tries = 0 ; while ( result == - 1 && tries < 200 ) { byte [ ] randomBytes = new byte [ 20 ] ; filenameRandom . nextBytes ( randomBytes ) ; String candidate = keyToString ( randomBytes ) ; ContentValues contentValues = new ContentValues ( ) ; contentValues . put ( "key" , keyString ) ; contentValues . put ( "filename" , candidate ) ; result = db . insert ( ATTACHMENTS_KEY_FILENAME , contentValues ) ; if ( result != - 1 ) { // i.e., insert worked, filename unique filename = candidate ; } tries ++ ; } if ( filename != null ) { return filename ; } else { throw new NameGenerationException ( String . format ( "Couldn't generate unique filename for attachment with key %s" , keyString ) ) ; } }
Iterate candidate filenames generated from the filenameRandom generator until we find one which doesn t already exist .