Vajira Lasantha Vajira Lasantha - 2 months ago 8
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

fileId
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
file_??_download.jpg
. It looks like
String.format()
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.

Thanks!

Answer

You have to do it instead:

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

or

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";

or

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