20

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.

If I type

Switch s = (Switch) findViewById(R.id.switch1);

it says findViewById is undefined for the type SecondActivity. The problem is Android doesn't allow me to get the value of switch in a class that extends Broadcast Receiver.

I want to know the state of switch, i.e, whether switch is on or off, but in second activity. How can I achieve it?

gegobyte
  • 4,945
  • 10
  • 46
  • 76
  • Possible duplicate: http://stackoverflow.com/a/10577852/2777098 – display name Oct 31 '14 at 14:00
  • @IsabelHM I have already told that Android doesn't recognizes findViewById in a class that extends Broadcast receiver. I have read that question, that is completely different. – gegobyte Oct 31 '14 at 14:01
  • 2
    Your BroadcastReceiver doesn't have a UI (and thus no switch), so it makes sense that it wouldn't let you `findViewById()`. – Bryan Herbst Oct 31 '14 at 14:06

3 Answers3

32

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);
JstnPwll
  • 8,585
  • 2
  • 33
  • 56
  • How can I add boolean value to preference and retrieve in SecondActivity. Can you please post code? – gegobyte Oct 31 '14 at 14:13
  • I am getting an error in SecondActivity. This is the error:- "The method getDefaultSharedPreferences(Context) in the type PreferenceManager is not applicable for the arguments (SecondActivity)". – gegobyte Oct 31 '14 at 14:16
  • Actually I am creating an app that blocks incoming call when switch is ON. I have posted a question with full code. Please have a look:- http://stackoverflow.com/questions/26673533/how-to-block-incoming-call-when-switch-widget-is-on – gegobyte Oct 31 '14 at 14:20
  • I thought `"SecondActivity"` was an Activity. All you need is a context, instead of `this` you can use `context` (passed in from the `onReceive` method). – JstnPwll Oct 31 '14 at 14:23
10

To access the value of the switch, you need to do the following:

((Switch) findViewById(R.id.switch_id)).isChecked();

BUT in a context of a BroadcastReceiver, you don't have really access to a layout, therefore you can't access the switch. You have to perform this ONLY within the Activity that inflates the layout that has the Switch.

You may have a BroadcastReceiver registered programmatically within an Activity, this is the only way I see this mixture of concepts working.

Alécio Carvalho
  • 13,481
  • 5
  • 68
  • 74
0

You can save the value in Preferences. Below class will be make easy for you to save data and retrive it from Preferences

public class SessionManager {

    private SharedPreferences pref;
    private static SessionManager sessionManager;




    public static SessionManager getInstance(Context context) {
        if(sessionManager == null){
            sessionManager = new SessionManager(context);
        }
        return sessionManager;
    }


    public SessionManager(Context context) {
        String PREF_NAME = context.getResources().getString(R.string.app_name);
        this.pref = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE);

    }


    /**
     * Getting value for key from shared Preferences
     *
     * @param key          key for which we need to get Value
     * @param defaultValue default value to be returned if key is not exits
     * @return It will return value of key if exist and defaultValue otherwise
     */
    public String getValueFromKey(String key, String defaultValue) {
        if (pref.containsKey(key)) {
            return pref.getString(key, defaultValue);
        } else {
            return defaultValue;
        }
    }


    /**
     * Setting value for key from shared Preferences
     *
     * @param key   key for which we need to get Value
     * @param value value for the key
     */
    public void setValueFromKey(String key, String value) {
        pref.putString(key, value).apply();
    }


    /**
     * Setting value for key from shared Preferences
     *
     * @param key   key for which we need to get Value
     * @param value value for the key
     */
    public void setFlagFromKey(String key, boolean value) {
        pref.putBoolean(key, value).apply();
    }


    /**
     * To get Flag from sharedPreferences
     *
     * @param key key of flag to get
     * @return flag value for key if exist. false if not key not exist.
     */
    public boolean getFlagFromKey(String key) {
        return pref.containsKey(key) && pref.getBoolean(key, false);
    }

}
Nikunj Peerbits
  • 785
  • 4
  • 12