简体   繁体   中英

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

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?

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
    }

PS: 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.

You can try with matches

Tests whether this string matches the given regularExpression. This method returns true only if the regular expression matches the entire input string.

if(getResources().getString(R.string.default_item_1).matches("@null")) 
{ 
     // Your logic
}
else
    {
     // Your logic
    }

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource.

Courtesy dynamic String using String.xml?

You can use method for this.

 public static boolean isNullString(String string) {
    try {
        if (string.trim().equalsIgnoreCase("null") || string.trim() == null || string.trim().length() < 0 || string.trim().equals("")) {
            return true;
        } else {
            return false;
        }
    } catch (Exception e) {
        return true;
    }
}

Use this method as

if(isNullStrind(your string value){
//true
write your code
}else{
//false
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM