-1

我是 android 开发的菜鸟,我正在尝试使用共享首选项在 onCreate 期间获取 double 的值。但是,我这样做的代码似乎只在我第一次重新启动我的应用程序时才有效。在随后的重新启动期间,代码不起作用并跳过我的代码的 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.
              }
4

2 回答 2

3

您应该在这里使用 String.equals(),而不是 ==。

if(savedporfoliocurrency=="usd"){

例如,请参阅 SO 问题Java String.equals vs ==

==,正如您所发现的,有时会起作用,但这不是您想要在这里做的。您要检查内容,而不是存储它们的位置。

于 2012-10-22T22:52:50.087 回答
1

改变:

savedporfoliocurrency=="usd"

savedporfoliocurrency.equals("usd")

并在类似的 manar 修复其他字符串比较

于 2012-10-22T22:52:47.053 回答