mercredi 15 juillet 2020

how to pass checkbox data to another activity

How to pass checkbox data from one activity to another? If the checkbox is checked/selected, it will pass data in a form of String from first activity to second activity. The second activity will get the String and set the text on _Job_fx, but why does other checkbox Strings appear when the checkbox wasn't check? My data bypass my condition and set text on _Job_fx. How to fix this?

first activity:

sharedPreferences = getSharedPreferences("Add_job_fx", MODE_PRIVATE);

_electric_item01 = (CheckBox) findViewById(R.id.electric_item01);
checkbox(_electric_item01);
_electric_item02 = (CheckBox) findViewById(R.id.electric_item02);
checkbox(_electric_item02);
_electric_item03 = (CheckBox) findViewById(R.id.electric_item03);
checkbox(_electric_item03);
_electric_item04 = (CheckBox) findViewById(R.id.electric_item04);
checkbox(_electric_item04);

    private void checkbox(final CheckBox check) {

        check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (check.isSelected()) {
                    //edit shared preference (put data)
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    //put data in shared preference
                    editor.putString(check.getText().toString(), check.getText().toString());
                    //apply changes to shared preference
                    editor.apply();
                }
                else {
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.remove(check.getText().toString());
                    editor.clear();
                    editor.apply();
                }
            }
        });
    }

second activity:

//shared preferences (Name, Mode)
sharedPreferences = getSharedPreferences("Add_job_fx", MODE_PRIVATE);
//get data from shared preference
s_electric_item01 = sharedPreferences.getString("Change lightbulb", "");
s_electric_item02 = sharedPreferences.getString("Change starter", "");
s_electric_item03 = sharedPreferences.getString("Change light set", "");
s_electric_item04 = sharedPreferences.getString("Change fan + regulator", "");
//pass data to container for view 
_Job_fx.setText("Job: " + s_electric_item01 +"\n"+ s_electric_item02 + "\n"+ s_electric_item03);



Aucun commentaire:

Enregistrer un commentaire