I have placed a switch widget in Main Activity, I also have a second activity that extends BroadcastReceiver. I want to get the boolean state of switch widget in second activity
Calling findViewById()
from an Activity can only access Views that are a part of the layout of that Activity. You cannot use it to search the layout of any other Activity.
Depending on your app design, you can use one of these:
1) Send the value of the Switch to SecondActivity via an Intent extra
In Activity:
Intent mIntent = new Intent(this, SecondActivity.class);
mIntent.putExtra("switch", s.isChecked());
startActivity(mIntent);
In SecondActivity:
boolean isChecked = getIntent().getBooleanExtra("switch", false);
2) Save the value to a preference on change, and read preferences in SecondActivity
In Activity:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor e = settings.edit();
e.putBoolean("switch", s.isChecked());
e.commit();
In SecondActivity:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
boolean isChecked = settings.getBoolean("switch", false);