Home > database >  SharedPreferences in fragment with button
SharedPreferences in fragment with button

Time:01-10

I have a TextView that stores a specific number of age and there are two buttons increasing that number and decreasing, after I set a specific number in the textview, I want to save it using SharedPreferences. What am I doing wrong? Just learning to program.



    public SharedPreferences pref;
    public final String save_key = "save_key";

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

TextView age = (TextView) v.findViewById(R.id.age);
        Button button_add_age = (Button) v.findViewById(R.id.button_add_age);
        button_add_age.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Integer.parseInt(age.getText().toString()) > 0) {
                    int age_value = Integer.parseInt(age.getText().toString())   1;
                    age.setText(String.valueOf(age_value));
                }
            }
        });

        Button button_remove_age = (Button) v.findViewById(R.id.button_remove_age);
        button_remove_age.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Integer.parseInt(age.getText().toString()) > 1) {
                    int age_value = Integer.parseInt(age.getText().toString()) - 1;
                    age.setText(String.valueOf(age_value));
                }
            }
        });

 Button saveButton = (Button) v.findViewById(R.id.save_button);
         saveButton.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 SharedPreferences.Editor edit = pref.edit();
                 edit.putString(save_key,age.getText().toString());
                 edit.apply();

             }
         });

return v;

CodePudding user response:

You can write to SharedPreference like the code below. Please read Save key-value data for more information.

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(save_key, age.getText().toString());
editor.apply();

CodePudding user response:

Not really sure what's your issue, since you haven't mentioned what's not working. But from the snippet, the SharedPreferences pref is not initialized.

It should be something like context.getSharedPreferences("my-shared-perferences", MODE_PRIVATE)

  •  Tags:  
  • Related