SharedPreferences CheckBox in fragment

126 views Asked by At

Hi i starded say I'm new of android and language in general, i have used the SharedPreferences for store different edittext but now i want store the check of one checkbox but i don't know how can store this value, i hope someone can help me.

public class FiveFragment extends Fragment {

EditText et133;


CheckBox ch1;


public FiveFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_five, container, false);

    SharedPreferences setting = this.getActivity().getSharedPreferences("PRESS", Context.MODE_PRIVATE);

    et133 = (EditText) view.findViewById(R.id.editText);

    ch1 = (CheckBox) view.findViewById(R.id.checkBox);

//NOW????

    et133.setText(setting.getString("value133", ""));



    return view;

}

public void onStop() {
    super.onStop();
    if (et133.getText() != null) {

        SharedPreferences setting = this.getActivity().getSharedPreferences("PRESS", 0);
        SharedPreferences.Editor editor = setting.edit();
        editor.putString("value133", et133.getText().toString());

//Now??? editor.apply();

    }
}

}

2

There are 2 answers

1
Murat Karagöz On

You can use a listener or do it in your onStop() method.

 ch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setting.edit().putBoolean("checkbox", isChecked).apply();
            }
        });

OR in your onStop()

 setting.edit().putBoolean("checkbox", ch1.isChecked).apply();
0
Shuyun6 On

Use editor.commit() after putString(),then values will be saved