In my values.xml, I have some string resources. But sometimes, I want to have a null value for that string resource for specific reasons.
How do I specify that string to have a null
value?
values.xml:
<string name="default_item_0">Some String</string>
<string name="default_item_1">@null</string>
Java code:
String item0 = context.getString(R.string.default_item_0);
String item1 = context.getString(R.string.default_item_1);
Expected:
String item0 = "Some String";
String item1 = null;
Actual:
String item0 = "Some String";
String item1 = "@0";
I tried the @null value, but it returns a string of @0
instead.
Is it possible to have a null
value in xml?
The purpose of strings. xml (and other *. xml resource files) is to regroup similar values in one place. This facilitates finding values that would be otherwise buried in the code.
String. xml file contains all the strings which will be used frequently in Android project. String. xml file present in the values folder which is sub folder of res folder in project structure.In Android Studio, we have many Views such as TextView,Button,EditText,CheckBox,RadioButton etc.
Let's start with the first part, @string . This is just a way of telling Android to look up a text value from a string resource file. In our case, Android Studio created a string resource file for us called strings.
As you know resources exist because they're supposed to be "something NOT null", and @null
is simply a reference resource with a zero-value id.
Is it possible to have a null value in xml?
Null value for string resources? No and honestly it doesn't seem reasonable
But in this case with your specific reasons I suggest you to add an empty string to resources:
<string name="empty"/>
Then you can check if it is empty or not :
String str = getString(R.string.empty);
if (TextUtils.isEmpty(str)) {
//do something
}
P.S: Earlier I used this approach to map indices to the correct items of an array, as you guess in my case some indices were skipped so I had to skip some array items as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With