android.content.SharedPreferences的getString(key,defValue)方法表现不如预期

时间:2011-10-27 06:22:39

标签: android

我是Android的新手,并且一直在尝试使用Android 2.3.3(API Level 10)模拟器上的微博客户端Yamba。众所周知,像twitter这样的微博有一个时间表,但如果没有用户的用户名和密码,就无法获取更新。因此,在TimelineActivity(主入口点)的onCreate()方法中,我有以下代码:

 if (yamba.getPrefs().getString("username", null) == null) {
        startActivity(new Intent(this, PrefsActivity.class));
        Toast.makeText(this, R.string.msgSetupPrefs, Toast.LENGTH_LONG).show();
    }

getprefs()方法将获取SharedPreferences对象,这里是getString的文档

 public abstract String getString (String key, String defValue)
 Since: API Level 1
 Retrieve a String value from the preferences.

 Parameters
 key    The name of the preference to retrieve.
 defValue   Value to return if this preference does not exist.
 Returns    Returns the preference value if it exists, or defValue. 
 Throws ClassCastException if there is a preference with this name that is not a String.

但事实并非如此。如果用户名为空,则getString方法将返回空字符串(“”),而不是如上定义的“defValue”。在我将第二个(null)更改为(“”)之后,它可以在用户启动应用程序时首先显示首选项视图。那么为什么这个方法不像doc说的那样表现呢?

3 个答案:

答案 0 :(得分:2)

当你说“如果用户名是空白的”时,你的意思是它已经被插入到没有值的首选项中,或者它从未被设置过? defValue是在prefs文件中没有匹配键的情况下返回的值。这有帮助吗?

答案 1 :(得分:0)

尝试使用yamba.getPrefs().getString("username", null).equals("") 共享首选项方法应适用于您的案例

答案 2 :(得分:0)

如果要同时捕获空字符串和空字符串,请附加.length()

(someobject.getMethod().length() == 0)