Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

aakarshrestha
aakarshrestha
6,509 Points

How to get the checked box checked after going back and forth from one activity to another?

How to get the checkbox checked after going back and forth from one activity to another?

I want to have the checkbox checked using baseadapter... but i am not able to do it. Any help is highly appreciated!

3 Answers

Jonas Samulionis
Jonas Samulionis
6,874 Points

Hi,

If you need a long term storage of the checked value you could probably store it using SharedPreference.

if the value shall only be stored in short basis (will be gone after the application is closed) you should use "Static class". I created example for you.

public class MainActivity extends AppCompatActivity {
    // Staitc boolean is set to false on app start.
    private static boolean neverChange = false;
    // Our checkbox and the button
    private CheckBox mCheckBox;
    private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mCheckBox = (CheckBox) findViewById(R.id.checkBox);
    mButton = (Button) findViewById(R.id.button);

    //Basicaly here the magic happens, if the user went back from the secondActivity and the boolean "neverChange" is true,
    //it will set our CheckBox to true. 
    if (neverChange == true) {
        mCheckBox.setChecked(true);
    }
    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, secondActivity.class);
            startActivity(intent);
        }
    });
    // The checkbox
    mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // Here we set our static boolean variable to true or false.
            if(!isChecked) {
                neverChange = false;
            } else {
                neverChange = true;
            }
        }
    });
}