2011-10-27 22 views
2

我是Android新手,一直在Android 2.3.3(API Level 10)仿真器上嘗試使用Yamba(微博客戶端)。正如我們所知,Twitter這樣的微博有一個時間表,但不會在沒有用戶的用戶名和密碼的情況下獲取更新。因此,在TimelineActivity(主入口點)的onCreate()方法,我有以下代碼:android.content.SharedPreferences'getString(key,defValue)方法的行爲與預期不符

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」。在將第二個(空)更改爲(「」)後,它將與用戶啓動應用程序時首先顯示的首選項視圖一起使用。那麼爲什麼該方法不像文檔所說的那樣?

+0

沒有什麼方法返回時,你變成 (」」)? – androidnoob

+0

對不起,讓我澄清一下,我將第二個空值更改爲「」,現在將執行if塊中的代碼 – manuzhang

回答

2

當你說「如果用戶名是空白的」,你的意思是它已經被插入到沒有值的首選項,或者它從來沒有被設置? defValue是在prefs文件中沒有匹配鍵時返回的值。這有幫助嗎?

+0

是的,我確實設置了默認的用戶名和密碼,它們都是空值 – manuzhang

+0

這很有道理。請記住,共享首選項基本上只是存儲事物的文本文件方法。它沒有一個null的概念。你只是用getString得到一個空字符串。要得到null,您需要從未插入任何帶有「用戶名」鍵的內容,或者先調用edit.remove(「username」); – akhalsa

+0

對不起,我再次調試,發現默認值尚未設置。密鑰設置在一個xml文件中。 – manuzhang

0

使用yamba.getPrefs().getString("username", null).equals("") 共享偏好方法嘗試應該工作的情況下

+0

使用equals是個好習慣,但「==」在這裏工作 – manuzhang

+1

是的,但'.equals()'最適合Strings。 '=='有時不可靠 – androidnoob

0

如果你想趕上null和空字符串追加。長度()

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

我認爲不是你可以調用任何可能會拋出NullPointerException的空字符串的方法 – manuzhang