0

I'm a newbie in Android development. Let me explain my problem. I've have a checkbox and a Button in my Main activity. When I Check(that is, enable) my checkbox and Click my Button below it, I'll be moving to another activity and as I click a button in the second activity, I come back to my main Activity. My problem is when I come back, the Checkbox remains UnChecked or Disabled. What do I do to retain its state even after coming back from the second activity? Please Help.

The CheckBox part of XML layout is:

<CheckBox
    android:id="@+id/ckBxAll"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ON" />

Skeleton code for Main activity:

Public class TestActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
LayoutInflater mInflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View mMainView = mInflater.inflate(R.layout.main, null);        
setContentView(mMainView);
 Enable_chkbox = (CheckBox)mMainView.findViewById(R.id.ckBxAll);
if(b_onResume==true)
    {
      Enable_chkbox.setChecked(b_onResume);
   }
Enable_chkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub




//do something



        });//Enable_chkbox
Compose_btn=(Button)findViewById(R.id.btnCompose);
        Compose_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent gotoComposeMessage=new Intent(TestActivity.this,ComposeMessage.class);
                startActivity(gotoComposeMessage);
            }
        });
}
@Override
    protected void onResume() {
      super.onResume();
     b_onResume=  Enable_chkbox.isChecked();

    }
   @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unregisterReceiver(myreceiver);
        this.finish();
      }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
       super.onSaveInstanceState(savedInstanceState);
       savedInstanceState.putBoolean("Enable_chkbox",true);       

    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onRestoreInstanceState(savedInstanceState);
        boolean myBoolean = savedInstanceState.getBoolean("Enable_chkbox");
    }  

}

My Second Activity:

public class ComposeMessage extends Activity{
    Button SaveSMS_btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.composemessage);
        SaveSMS_btn=(Button)findViewById(R.id.btnSave);
        SaveSMS_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent gotoHome=new Intent(getApplicationContext(),BlockTestActivity.class);
                Bundle BundleToCarryMessage = new Bundle();
                EditText EnterSMS_edt=(EditText)findViewById(R.id.edtEnterSMS);
                BundleToCarryMessage.putString("Message", EnterSMS_edt.getText().toString());
                gotoHome.putExtras(BundleToCarryMessage);
                startActivity(gotoHome);
            }
        });

    }

}

The XML file used in the second activity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/edtEnterSMS"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save" />

</LinearLayout>
Deepthi
  • 875
  • 1
  • 12
  • 20

3 Answers3

6

There is another way. You need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like this:

The next code is for saving the check box state, before moving to the second activity:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {

  savedInstanceState.putBoolean("MyCheckBox", enable);

  super.onSaveInstanceState(savedInstanceState);
}

And this is when you restore the check box state:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);

  boolean myBoolean = savedInstanceState.getBoolean("MyCheckBox");

}

EDIT:

public class TestActivity extends Activity implements OnCheckedChangeListener, OnClickListener  {

        private CheckBox Enable_chkbox;
        private View mMainView;
        private Button Compose_btn;
        private boolean myBoolean = false;;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            LayoutInflater mInflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
            mMainView = mInflater.inflate(R.layout.main, null);        
            setContentView(mMainView);
            initView();
        }

        private void initView(){

             Enable_chkbox = (CheckBox)mMainView.findViewById(R.id.ckBxAll);
             Enable_chkbox.setOnCheckedChangeListener(this);
             Compose_btn=(Button)mMainView.findViewById(R.id.btnCompose);
             Compose_btn.setOnClickListener(this);
        }

        @Override
        protected void onResume() {
          super.onResume();
          Enable_chkbox.setChecked(myBoolean);

        }

        @Override
        public void onSaveInstanceState(Bundle savedInstanceState) {
           super.onSaveInstanceState(savedInstanceState);
           savedInstanceState.putBoolean("Enable_chkbox", Enable_chkbox.isChecked());      
        }

        @Override
        protected void onRestoreInstanceState(Bundle savedInstanceState) {
            super.onRestoreInstanceState(savedInstanceState);
            myBoolean = savedInstanceState.getBoolean("Enable_chkbox");
        }

        @Override
        public void onClick(View arg0) {
            //do something
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            //do something
        }  
}

'

Hope it helps.

Ofir A.
  • 3,112
  • 11
  • 57
  • 83
2

For all general purposes you have to save the state of of your checkboxes and radio buttons when you leave an activity, and restore them when you come back to it.
To do this we generally use shared preferences. We save the the state of the buttons in the onPause() method and restore the state in the onResume() method.
To use the shared preferences you can do something like:

SharedPreferences prefs = this.getSharedPreferences(
      "com.example.app", Context.MODE_PRIVATE);

To read preferences:

String dateTimeKey = "com.example.app.datetime";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

To edit and save preferences

Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).commit();

See more example at this blog.
With the above code placed in the correct method (onPause and onResume) you can restore the state of your buttons.

Urban
  • 2,201
  • 24
  • 52
0

Switch to Second Activity using startActivityforResult. When you switch using this you dont finished the current activity so it stored the state of the activity.

Krishnakant Dalal
  • 3,568
  • 7
  • 34
  • 62