Vajira Lasantha
Vajira Lasantha

Reputation: 2513

Android String.format() Returns Question Mark (??)

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!

Upvotes: 0

Views: 353

Answers (2)

Joni
Joni

Reputation: 111259

String.format will use the digits for the default locale which are not necessarily 0-9. Use the version that permits setting a locale, and pass in Locale.ROOT.

String.format(Locale.ROOT, "%02d", fileId)

Upvotes: 2

Augusto Carmo
Augusto Carmo

Reputation: 4964

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

Upvotes: 2

Related Questions