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

Cannot save RadioGroup's selected Item in sharedPreferences - Fragment

我有 fragment 和内部片段,我想将选定的 RadioGroup (Male/Female) 选项存储在 SharedPreferences 中。 按照我试过的代码,如果我在 Activity 中使用它,它会起作用,但它在 Fragment.

中不起作用

在加载和插入所选选项的 int 值时,它 returns 正确的值 - Male = 0,Female = 1,但在加载数据期间,它崩溃了 NullPointerException 以下声明

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

我尝试在 Whosebug 上搜索很多解决方案,但没有成功。 对此有什么建议或帮助吗?谢谢。

 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);


        }

    }
}

您不需要在每次要使用视图时都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);


        }

    }
}