0

I am currently building an App which is almost ready for release, but I got a problem I'am stuck with for quiet a while. My App contains a button that once clicke changes its color to either red or green which indicates which can change dynamically. I now wan't to save the state of my Button with sharedPreferences. But everything I try fails. I know this sounds rude but it would be very cool if you could show me how you would do it.

So thats my class with the data for my item is stored in

public class MyItem {

private String taskText;




public MyItem(String line1) {
    taskText = line1;



}

public String getTaskText() {
    return taskText;
}


}

And this is the OnClick Method I created which changes the color of my Button. I am trying to save clicks

mButton = itemView.findViewById(R.id.button3);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clicks++;

                if (clicks % 2 == 0)
                    mButton.setBackgroundResource(R.drawable.button_green);
                else
                    mButton.setBackgroundResource(R.drawable.button_red);
            }
        });
obri
  • 11
  • 6
  • 3
    Does this answer your question? [How to use SharedPreferences in Android to store, fetch and edit values](https://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values) – haliltprkk May 02 '20 at 20:29

1 Answers1

0

No need to save integer, instead save some string to set color:

When you click the button, save the color as string:

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clicks++;

            if (clicks % 2 == 0)
                mButton.setBackgroundResource(R.drawable.button_green);

                //save as green
               SharedPreferences.Editor editor = getSharedPreferences("button", 
               MODE_PRIVATE).edit();
               editor.putString("color", "green");
               editor.apply();
            else
                mButton.setBackgroundResource(R.drawable.button_red);

                //save as red
               SharedPreferences.Editor editor = getSharedPreferences("button", 
               MODE_PRIVATE).edit();
               editor.putString("color", "red");
               editor.apply();
        }
    });

Now in your activity in onCreate():

Under this line:

mButton = findViewById(......);

Add this:

//get the color that was saved
SharedPreferences pref = getSharedPreferences("button", MODE_PRIVATE); 
String color = pref.getString("color", "default");


if(color.equals("green")){
//color was green
mButton.setBackgroundResource(R.drawable.button_green);
}else{
//color was red
mButton.setBackgroundResource(R.drawable.button_red);
}
Hasan Bou Taam
  • 4,017
  • 2
  • 12
  • 22