user10466372
user10466372

Reputation: 1

getting checkbox to output yes if checked and no if unchecked

I have a single checkbox. I need it to see the result in a textView. It needs to say yes if checked and no if unchecked.I am able to get it to show true of false if checked/unchecked but I need it to say yes/no. The checkbox text asks a yes or no question. I have to use shared preferences. This is what i have and its returning true and false:

public void addStudent(View view){
   Boolean major;
   if(Major.isChecked())
   {
       major = true;
   }
   else
   {
       major = false;
   } 

   SharedPreferences sharedPreferences = 
   getSharedPreferences("StudentInfo", Context.MODE_PRIVATE);
   SharedPreferences.Editor editor = sharedPreferences.edit();


   editor.putString("memberFirstName", firstName.getText().toString());
   editor.putString("memberLastName", lastName.getText().toString());
   editor.putInt("sId", studentId);
   editor.putBoolean("major", major);
   editor.commit();
   firstName.setText("");
   lastName.setText("");

   Toast.makeText(this, "Student Added!", Toast.LENGTH_SHORT).show();
   }
   public void viewMembers(View view)
   {

   SharedPreferences sharedPreferences = 
   getSharedPreferences("StudentInfo", Context.MODE_PRIVATE);

   String first = sharedPreferences.getString("memberFirstName", "");
   String last = sharedPreferences.getString("memberLastName", "");
   int id = sharedPreferences.getInt("sId", 0);
   Boolean MajorCis = sharedPreferences.getBoolean("major", true);

  viewStudents.setText("Student Name:"+ " " +first + " " + last + "\n" 
   + "Student Id: " + id + "\n" +"CIS Major: " + MajorCis);

Upvotes: 0

Views: 319

Answers (2)

Lovekush Vishwakarma
Lovekush Vishwakarma

Reputation: 3169

please use this Sample code

CheckBox checkbox=(CheckBox)findViewById(R.id.checkbox);
        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    textview.setText("YES");
                }else{
                    textview.setText("NO");
                }
            }
        });

Upvotes: 0

Krishna Sharma
Krishna Sharma

Reputation: 2877

Simply set the text "Yes/No" based on checkbox status.

textView.setText(checkbox.isChecked()?"Yes":"No");

Upvotes: 0

Related Questions