Vajira Lasantha Vajira Lasantha - 4 months ago 14
Android Question

Android String.format() Returns Question Mark (??) [FIXED]

I have an app which downloads some files from internet. The source file name is dynamically generated depending on user selection. I use following method to create source file name. Note that

is an integer (1-99).

final String fileName = "file_" + String.format("%02d", fileId) + "_download.jpg";

The issue is I have seen some users are unable to download files (and of course they leave 1 start ratings :( ). When I check my server log I see some download requests came with file names like
. It looks like
has returned
instead of two digit number.

I searched everywhere and could not find a solution for this. Can anybody tell me what's wrong with this code? I could not even re-produce this error on any of my devices.



You have to do it instead:

final String fileName = "file_" + String.format("%d", fileId) + "_download.jpg";


final String fileName = "file_" + fileId + "_download.jpg";

if you really want only the two last digits, do it:

int formattedFileId = fileId % 100;
final String fileName = "file_" + (formattedFileId < 10 ? '0' : '') + String.format("%d", formattedFileId) + "_download.jpg";


int formattedFileId = fileId % 100;
final String fileName = "file_" + (formattedFileId < 10 ? '0' : '') + formattedFileId + "_download.jpg";