Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Handling integer (%1$d) and String (%1$s) arguments for Right to Left languages like Arabic

Tags:

android

My strings.xml has a few strings in the following format

No new message in last %1$d days.

I use them in Java code as follows: String.format(getString(R.string.msg_str), 3);

And I successfully get "No new message in last 3 days."

Now how do I put the integer argument part in above string in values-ar -> strings.xml file for arabic ?

I have tried putting it in few ways like %1$d or d$1% or \u200F%1$d etc but nothing seems to work. I am not able to get the argument correctly printed to 3. Example: لا توجد رسالة جديدة في آخر d$1% أيام.

On the Java code part I tried String.format(Locale.getDefault(),getString(R.string.msg_str), 3);

The output I want for the above string when phone language is set to arabic is as follows: لا توجد رسالة جديدة في آخر 3 أيام.

PS: above is the tranlation from google translator.

like image 844
jindal.bit Avatar asked Oct 11 '25 19:10

jindal.bit


1 Answers

I took the text from your question and pasted it into my strings.xml file:

enter image description here

When I run my app, I get a crash right away. All it does is:

    TextView textView = (TextView) findViewById(R.id.text);
    textView.setText(getString(R.string.formatting, 6));

This is the crash:

E/AndroidRuntime( 5739): Caused by: java.util.UnknownFormatConversionException: Conversion: أ
E/AndroidRuntime( 5739):  at java.util.Formatter$FormatToken.unknownFormatConversionException(Formatter.java:1399)
E/AndroidRuntime( 5739):  at java.util.Formatter$FormatToken.checkFlags(Formatter.java:1336)
E/AndroidRuntime( 5739):  at java.util.Formatter.transform(Formatter.java:1442)
E/AndroidRuntime( 5739):  at java.util.Formatter.doFormat(Formatter.java:1081)
E/AndroidRuntime( 5739):  at java.util.Formatter.format(Formatter.java:1042)
E/AndroidRuntime( 5739):  at java.util.Formatter.format(Formatter.java:1011)
E/AndroidRuntime( 5739):  at java.lang.String.format(String.java:1999)

Next, I highlighted the format argument (d$1%), deleted it, and retyped it (by pressing % 1 $ d). My string now looks like this:

enter image description here

Now when I run my app, it works just fine:

enter image description here

Since the two strings look identical to me, I assume that there are some non-printing characters in the first one that relate to text direction. These non-printing characters are probably confusing the parsing of the string's format arguments.

like image 113
Ben P. Avatar answered Oct 14 '25 11:10

Ben P.