javaandroidsharedpreferencesandroid-button

CHANGING the text of a button with SHARED PREFERENCES android studio


I'm making a simple app that has a button. When a pokemon is caught, I want the text to be "release" and when it's not, to be "catch!". When clicking the button, I want to change caught from true to false or vice-versa.

For now, i've done this (it doesn't work as I expected):

    public void toggleCatch(View view) {

        boolean caught;

        String name = nameTextView.getText().toString();

        SharedPreferences captured = getSharedPreferences("pokemon_name",Context.MODE_PRIVATE);

        if (captured.contains (name) ){
            catch_button.setText("Release");
            caught=true;
        }
        else{
            catch_button.setText("Catch!");
            caught=false;
        }

        if (caught) {
            getPreferences(Context.MODE_PRIVATE).edit().putString("pokemon_name", name).commit();
        } else {
            getPreferences(Context.MODE_PRIVATE).edit().remove(name).commit();
        }

    }

I would be very thankful if someone can help me!

I'm lost so I don't know if I'm on the correct path, my code is probably completely wrong.


Solution

  • I guess here is what you want:

    In your app, you have an EditText that allows users to input pokemon name. When users click on the toggle catch button,

    Solution

    public void toggleCatch(View view) {
        String name = nameTextView.getText().toString().trim();
        SharedPreferences captured = getSharedPreferences("pokemon_name", Context.MODE_PRIVATE);
        boolean caught = captured.contains(name);
        if (caught) {
            captured.edit().remove(name).apply();
            catch_button.setText("Release");
        } else {
            captured.edit().putBoolean(name, true).apply();
            catch_button.setText("Catch!");
        }
    }