开发者

Default value on Bundle.getString(String key)

开发者 https://www.devze.com 2023-02-09 00:48 出处:网络
I\'ve just noticed that, while most of getters from a Bundle have the possibiliy of including a default value, in case the key doesn\'t exist in that particular bundle instance, getString does not hav

I've just noticed that, while most of getters from a Bundle have the possibiliy of including a default value, in case the key doesn't exist in that particular bundle instance, getString does not have that possibility, returning null if that case.

Any ideas on why is that and if there is some way of easy solution to that (by easy I mean not having to check each individual value or extending the Bundle class).

As a开发者_JS百科n example, right now you have only this:

bundle.getString("ITEM_TITLE");

While I would like to do:

bundle.getString("ITEM_TITLE","Unknown Title");

Thanks!


Trojanfoe has the best solution if that is what you want, though once you get into dealing with defaults for other datatypes you'll have to do the same thing for them all.

Another solution would be to check to see if the bundle contains the key:

String myString = bundle.containsKey("key") ? bundle.getString("key") : "default";

It's not as nice as a function, but you could always wrap it if you wanted.


You'll have to wrap it yourself:

public String getBundleString(Bundle b, String key, String def)
{
    String value = b.getString(key);
    if (value == null)
        value = def;
    return value;
}


Note: http://developer.android.com/reference/android/os/Bundle.html

public String getString (String key, String defaultValue)

Since: API Level 12

EDIT this function has moved to BaseBundle: here


Another solution is to check for null:

String s = bundle.getString("key");
if (s == null) s = "default";

This is better than csaunders' solution because the Bundle can contain the respective key but it can be of a different type (for example an int), in which case his solution would result myString in being null, instead of "default".

0

精彩评论

暂无评论...
验证码 换一张
取 消