2012-10-22 138 views
-1

我是android開發的小菜鳥,我正嘗試在onCreate期間使用共享偏好來獲取double的值。但是,我這樣做的代碼似乎只在我第一次重新啓動我的應用程序時才起作用。在此期間,隨後的重新啓動代碼不起作用並跳過我的代碼的if/else部分。這是非常令人沮喪的,因爲如果一次有效,它應該每次都有效。任何幫助是極大的讚賞。爲什麼我的if/else語句不起作用?

public void LoadPreferences(){ 
          double portfoliocurrency1 = null; 
      SharedPreferences portfoliopreferences = getPreferences(MODE_PRIVATE); 
      String isuser1created = portfoliopreferences.getString("U1C", ""); 
      if(isuser1created.equals("yes")){   
       String savedportfolioname = portfoliopreferences.getString("PN1", ""); 
       String saveddenomination = portfoliopreferences.getString("DN1", ""); 
       String savedporfoliocurrency = portfoliopreferences.getString("PC1", ""); //<--Always either "usd", "inr", or "eur". 
       Log.d("test","SPConLoad=" + savedporfoliocurrency); //<--Returns correct value on every restart. 
       Log.d("test","USD=" + currencyUSD); //<--Returns correct value on every restart. 
       Log.d("test","EUR=" + currencyEUR); //<--Returns correct value on every restart. 
       pn1 = savedportfolioname; 
       denomination1 = saveddenomination; 
       if(savedporfoliocurrency=="usd"){ //<--If/else statement only works on first restart. For some reason it is skipped on subsequent restarts. 
        portfoliocurrency1 = currencyUSD; 
        Log.d("test","PC1USD=" + currencyUSD); //<--Returns correct value on first restart. 
       }else if(savedporfoliocurrency=="eur"){ 
        portfoliocurrency1 = currencyEUR; 
        Log.d("test","PC1EUR=" + currencyEUR); //<--Returns correct value on first restart. 
       }else if(savedporfoliocurrency=="inr"){ 
        portfoliocurrency1 = currencyINR; //<--Returns correct value on first restart. 
       } 
       Log.d("test","PC1onLoad=" + portfoliocurrency1); //<-- Only returns correct value during first restart. Always returns null on subsequent restarts. 
       } 
+0

看看http://stackoverflow.com/questions/767372/java-string-equals-versus – vfcosta

回答

3

您應該使用String.equals()在這裏,不是== 。

if(savedporfoliocurrency=="usd"){ 

例如參見SO問題Java String.equals versus ==

==,正如你發現的那樣,有時會起作用,但這不是你想要在這裏做的。你想檢查的內容,而不是他們存儲的位置。

+0

謝謝。剛剛嘗試過,它像一個魅力。我花了最後一小時試圖弄清楚什麼是錯的。再次感謝。 –

1

變化:

savedporfoliocurrency=="usd" 

savedporfoliocurrency.equals("usd") 

,並在相似的馬納爾修復等字符串比較

相關問題