无法在sharedPreferences中保存RadioGroup的所选项目 - 片段

时间:2016-03-21 23:18:46

标签: android android-sharedpreferences

我有fragment和内部片段,我想在SharedPreferences中存储所选择的RadioGroup(男/女)。 我尝试过以下代码,如果我在Activity中使用它,它可以正常工作,但它在Fragment中无效。

在加载和插入所选择的int值时,它返回正确的值 - Male = 0,Female = 1,但在加载数据期间,它崩溃了 以下陈述中的NullPointerException

 if (i >= 0) 
         ((RadioButton) ((RadioGroup) getActivity().findViewById(R.id.genderSelect)).getChildAt(i)).setChecked(true);

我已尝试在stackoverflow上搜索大量解决方案,但没有运气。 对此有何建议或帮助?谢谢。

 public class MyFragment extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

     View rootView = inflater.inflate(R.layout.profile_fragment,container,false);

    //Initializing views
    saveButton = (Button) rootView.findViewById(R.id.buttonSave);
    cancelButton = (Button) rootView.findViewById(R.id.buttonCancel);

    userGender = (RadioGroup) rootView.findViewById(R.id.genderSelect);

    loadProfileFields();
   return rootView;
   }


 private void saveProfile() {

    savedFileData = getActivity().getSharedPreferences(SHARED_PREF_FILE_NAME,Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = savedFileData.edit();
 RadioGroup localRadioGroup = (RadioGroup) getActivity().findViewById(R.id.genderSelect);
    editor.putInt(preference_key_profile_gender,
             localRadioGroup.indexOfChild(getActivity().findViewById(localRadioGroup.getCheckedRadioButtonId())));
  editor.apply();
 }


 private void loadProfileFields() {

    SharedPreferences loadProfile = getActivity().getSharedPreferences(SHARED_PREF_FILE_NAME, Context.MODE_PRIVATE);
    if(loadProfile != null){

        int i = loadProfile.getInt(preference_key_profile_gender, -1);
       // i gives me the right value, but it throws NullPointerExc inside If statement
        if( i >= 0){

                ((RadioButton) ((RadioGroup) getActivity().findViewById(R.id.genderSelect)).getChildAt(i)).setChecked(true);


        }

    }
}

1 个答案:

答案 0 :(得分:0)

每次要使用视图时,您都不需要findViewById()。 改变你的方法 -

private void saveProfile() {

    savedFileData = getActivity().getSharedPreferences(SHARED_PREF_FILE_NAME,Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = savedFileData.edit();

    editor.putInt(preference_key_profile_gender,
             userGender.indexOfChild(userGender.getCheckedRadioButtonId());
  editor.apply();
 }


 private void loadProfileFields() {

    SharedPreferences loadProfile = getActivity().getSharedPreferences(SHARED_PREF_FILE_NAME, Context.MODE_PRIVATE);
    if(loadProfile != null){

        int i = loadProfile.getInt(preference_key_profile_gender, -1);
       // i gives me the right value, but it throws NullPointerExc inside If statement
        if( i >= 0){

                ((RadioButton)userGender.getChildAt(i)).setChecked(true);


        }

    }
}