Reputation: 245
Global Variable:
SharedPreferences prefs;
SharedPreferences.Editor editor;
Saved during onDestory()
:
editor.putInt("InfType", rgTypeOfInf.getCheckedRadioButtonId()); //saving value
Being called during onCreate()
:
rgTypeOfInf = (RadioGroup) mFrame2.findViewById(R.id.rgType);
rgTypeOfInf.check(prefs.getInt("InfType", 2131230725)); //retrieving the value
How can I check when my app loads to see if the saved variable exist or if it's null
. If it exist, check the radio button of the radiogroup otherwise if it's null
, check the radiogroup[0] position by default?
My XML file:
<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>
Upvotes: 1
Views: 734
Reputation: 3489
Put:
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);
Retrieve:
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();
}
Havent tested
Used:
http://developer.android.com/guide/topics/ui/controls/radiobutton.html http://developer.android.com/reference/android/content/SharedPreferences.html#getInt(java.lang.String,%20int)
Upvotes: 1
Reputation: 7051
So you have a 'default' setting already if its null
See, your rgTypeOfInf.check(prefs.getInt("InfType", 2131230725));
has 2131230725 as the default value of the pref if it does not exist.
So, you can set it to something like -1, then say
int type = prefs.getInt("InfType", -1);
if (type == -1){
//was never set
} else{
//...
}
Upvotes: 2