code: 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));
          }
      }
docs: Iterate candidate filenames generated from the filenameRandom generator
  until we find one which doesn't already exist.
  
  We try inserting the new record into attachments_key_filename to find a
  unique filename rather than checking on disk filenames. This is because we
  can make use of the fact that this method is called on a serial database
  queue to make sure our name is unique, whereas we don't have that guarantee
  for on-disk filenames. This works because filename is declared
  UNIQUE in the attachments_key_filename table.
  
  We allow up to 200 random name generations, which should give us many millions
  of files before a name fails to be generated and makes sure this method doesn't
  loop forever.
  
  @param db database to use
  @param keyString blob's key