Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify null value for a string resource in xml in Android?

Tags:

java

android

xml

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?

like image 678
Poly Bug Avatar asked Apr 11 '16 06:04

Poly Bug


People also ask

Why do we store strings as resources 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.

What is string xml file in Android?

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.

Which tells Android to look up a text value from the string resource file?

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.


1 Answers

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.

like image 181
Farshad Tahmasbi Avatar answered Sep 19 '22 08:09

Farshad Tahmasbi