2013-08-06 30 views
1

全局變量:在onDestory()保存看到,如果一個SharedPreference變量爲空或不是

SharedPreferences prefs; 
SharedPreferences.Editor editor; 

editor.putInt("InfType", rgTypeOfInf.getCheckedRadioButtonId()); //saving value 

被稱爲中onCreate()

rgTypeOfInf = (RadioGroup) mFrame2.findViewById(R.id.rgType); 
rgTypeOfInf.check(prefs.getInt("InfType", 2131230725)); //retrieving the value 

我如何檢查時我的應用程序加載以查看保存的變量是否存在或者是否爲null。如果存在,請檢查radiogroup的單選按鈕,否則如果它是null,默認情況下檢查radiogroup [0]位置?

我的XML文件:

<RadioGroup 
     android:id="@+id/rgType" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" > 
     <RadioButton 
      android:id="@+id/rbBridge" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:checked="true" 
      android:text="Bridge" /> 
     <RadioButton 
      android:id="@+id/rbTunnel" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Tunnel" /> 
     <RadioButton 
      android:id="@+id/rbHighway" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Highway" /> 
    </RadioGroup> 
+0

['SharedPreferences#含有(String鍵)'](http://developer.android.com/reference/android/content/SharedPreferences.html#contains%28java.lang.String%29 )? – zapl

回答

1

地說:

int checked = -1; 
RadioGroup rg = (RadioGroup) findViewById(R.id.rgType); 
for(int i = 0; i < rg.getChildCount(); i++){ 
    if(((RadioButton)rg.getChildAt(i)).isChecked()){ 
    checked = i; 
    } 
} 
editor.putInt("InfType", checked); 

檢索:

int InfType = prefs.getInt("InfType", -1); 
RadioGroup rg = (RadioGroup) findViewById(R.id.rgType); 
if(InfType > -1) { 
    ((RadioButton)rg.getChildAt(InfType)).toggle(); 
} else{ 
    ((RadioButton)rg.getChildAt(0)).toggle(); 
} 

還沒有測試

使用:

http://developer.android.com/guide/topics/ui/controls/radiobutton.html http://developer.android.com/reference/android/content/SharedPreferences.html#getInt(java.lang.String,%20int)

+0

您是否知道如何將該值重置爲默認值? –

+0

@ZahidH刪除存儲的值 –

+0

我不能從'onCreate()'中的每個代碼中取出'RadioGroup rg =(RadioGroup)rgTypeOfInf;',因爲我之前已經調用它了? (Nevermind它正在崩潰我的應用程序) –

2

所以,你有一個「默認」設置已如果空

看,你的rgTypeOfInf.check(prefs.getInt("InfType", 2131230725));有2131230725彷彿不存在,把選項的默認值。

所以,你可以將它設置成類似-1,然後說

int type = prefs.getInt("InfType", -1); 

if (type == -1){ 
    //was never set 
} else{ 
    //... 
} 
+0

我在我的問題中添加了XML文件。默認情況下'Bridge'是自動選擇的。因此,例如,我選擇了'隧道'作爲選項,我離開視圖並返回,應該檢查'隧道',因爲我保存了該值。如果我第一次來到應用程序,應該檢查'Bridge',因爲它是默認的,除非我改變它。但是當我加載我的應用程序時,組中的單選按鈕沒有被選中。 –

+0

你記得做'editor.commit();' – VicVu

+0

是的,我做了...謝謝你的幫助。 –

相關問題