4

I am querying a collection for documents using below code. Document names are same as device names. The device name is passed to the document from an API I am getting an error when a device name contains letter "/" like Motorola C380/C385. I get an error

java.lang.IllegalArgumentException: Invalid document reference. Document references must have an even number of segments, but Mobiles/Motorola C380/C385 has 3

I know I am getting this error because FireStore considers the name C385 after slash as a collection inside a document. I want to know how to get rid of situations like this when a document name can contain a "/" should I check and remove this before inserting it into my collection or is there any better solution?

firebaseFirestore.collection("Mobiles").document(response.body().get(finalI).getDeviceName())
Asghar Nazir
  • 329
  • 5
  • 23

3 Answers3

4

try this

response.body().get(finalI).getDeviceName().toString().replace("/","_")
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
2

The simplest method I can think of, is before you add the data to the database to find that forbidden / symbol and replace it with an allowed one, let's say - (minus).

String deviceName = response.body().get(finalI).getDeviceName().replaceAll("/", "-");

And then simply use in your reference like this:

firebaseFirestore.collection("Mobiles").document(deviceName);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
0

A possibility can be

Make sure your document name is not empty in my case it was empty then i also got the same error:

eg:-

firebaseFirestore.collection("CollectionName").document("");

The above code will give the error:

java.lang.IllegalArgumentException: Invalid document reference. 
Document references must have an even number of segments, but users has 1
Deven
  • 3,078
  • 1
  • 32
  • 34