2012-12-06 89 views
0

我該如何修改這段代碼?簡單代碼管理SharedPreferences

prefsDisplay = getSharedPreferences("spinnerSelection", 
      Context.MODE_PRIVATE); 
    prefsPlan = getSharedPreferences("spinnerSelection1", 
      Context.MODE_PRIVATE); 

    if (prefsDisplay.getInt("spinnerSelection", 0) == 0) { 
     s1 = 0; 
    } else if (prefsDisplay.getInt("spinnerSelection", 0) == 1) { 
     s1 = 1; 
    } else if (prefsDisplay.getInt("spinnerSelection", 0) == 2) { 
     s1 = 2; 
    } else if (prefsDisplay.getInt("spinnerSelection", 0) == 3) { 
     s1 = 3; 
    } else { 
     s1 = 0; 
     DP.BreakdownMonths = 0; 
    } 

    if (prefsPlan.getInt("spinnerSelection1", 0) == 0) { 
     s2 = 0; 
    } else if (prefsPlan.getInt("spinnerSelection1", 0) == 1) { 
     s2 = 1; 
    } else if (prefsPlan.getInt("spinnerSelection1", 0) == 2) { 
     s2 = 2; 
    } else { 
     s2 = 0; 
     DP.PlanType = "highint"; 
    } 

基本上,我在做什麼,當應用程序登錄時,我希望它檢查SharedPreferences。如果它找到一個值,它將分配它,否則它默認爲一個值。

+1

'S1 = prefsDisplay.getInt( 「spinnerSelection」,0);'相同將s2 –

+0

看來我可以只是這樣做:'如果(sharedPreference爲空){分配值。 }'完成 – KickingLettuce

回答

3

下面做你的代碼做什麼。使用分配給共享首選項的值,如果爲空,則分配0並同時分配DP。

prefsDisplay = getSharedPreferences("spinnerSelection", 
     Context.MODE_PRIVATE); 
prefsPlan = getSharedPreferences("spinnerSelection1", 
     Context.MODE_PRIVATE); 

s1 = prefsDisplay.getInt("spinnerSelection", -1); 
if(s1 < 0) { 
    s1 = 0; 
    DP.BreakdownMonths = 0; 
} 

s2 = prefsPlan.getInt("spinnerSelection1", -1); 
if(s2 < 0) { 
    s2 = 0; 
    DP.PlanType = "highint"; 
} 
+0

我會用這個,謝謝! – KickingLettuce

+0

很高興我能幫到你。只要確保你的問題包含正確的代碼 - 'BreakdownMonths'和'PlanType'是*只有*分配,如果首選項是空的開始,正確的? – 323go

1

使用switchcase定義各自的if語句,並使用default分配,如果它不匹配任何if語句的。

例如:

int month = 8; 
    String monthString; 
    switch (month) { 
     case 1: monthString = "January"; 
       break; 
     case 2: monthString = "February"; 
       break; 
     case 3: monthString = "March"; 
       break; 
     case 4: monthString = "April"; 
       break; 
     case 5: monthString = "May"; 
       break; 
     case 6: monthString = "June"; 
       break; 
     case 7: monthString = "July"; 
       break; 
     case 8: monthString = "August"; 
       break; 
     case 9: monthString = "September"; 
       break; 
     case 10: monthString = "October"; 
       break; 
     case 11: monthString = "November"; 
       break; 
     case 12: monthString = "December"; 
       break; 
     default: monthString = "Invalid month"; 
       break; 
    } 
    System.out.println(monthString);