user993074
user993074

Reputation: 93

Save value from checkbox and use in another view

i want to save the value boolean true or false from checked checkbox and use it in another view.

here is what i want to do

in my activity where i have the checkbox, it looks like this

checkBoxAdvanced = (CheckBox) findViewById(R.id.checkbox_advanced);
    checkBoxNeutral = (CheckBox) findViewById(R.id.checkbox_neutral);

    checkBoxAdvanced.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkBoxNeutral.setChecked(false);
            checkState = true;
            sendCheckState();
        }
    });

    checkBoxNeutral.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkBoxAdvanced.setChecked(false);

        }
    });

    public void sendCheckState(){
    Intent intent = new Intent(SettingsActivity.this, MainActivity.class);
    intent.putExtra("checkValue", value);
    startActivity(intent);
}

and in my MainActivity i want to use the value to either hide or show an text depending on the value

anyone who can help with this?

Upvotes: 0

Views: 45

Answers (2)

Ale
Ale

Reputation: 86

You can use SharedPreferences to saved the value and access to it elsewhere, using the same name SHARED_PREFERENCES_NAME in your project:

checkBoxAdvanced.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        checkBoxNeutral.setChecked(false);
        checkState = true;

        SharedPreferences sp = this.getSharedPreferences(SHARED_PREFERENCES_NAME,Context.MODE_PRIVATE);
        SharedPreferences.Editor spEdit = sp.Edit();
        spEdit.putBoolean("checkState",true);
        spEdit.apply();
        Intent intent = new Intent(SettingsActivity.this, MainActivity.class);
        startActivity(intent);
    }
});

To access to the value of checkState in other Activity or Service:

SharedPreferences sp = this.getSharedPreferences(SHARED_PREFERENCES_NAME,Context.MODE_PRIVATE);
boolean checkState = sp.getBoolean("checkState",false);

Upvotes: 1

Sandeep dhiman
Sandeep dhiman

Reputation: 1921

Get this value in your MainActivity class

 boolean flag =  getIntent().getBooleanExtra("checkValue",false);

 if(flag){
     // hide or show your view here
   }

Upvotes: 1

Related Questions