Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing findViewById inside BroadcastReceiver
    text
    copied!<p>I'm creating an sms app that handles receiving sms operation for 2 user defined lists. For each list I created an activity, and xml file such as favourite_list.xml and contact_list.xml. Inside these xml files there are 2 toggle buttons. What I'm trying to do is, whenever an sms receives, learn the status (on/off) of every toggle button.</p> <p>Here is my SmsReceiver class</p> <pre><code>import android.os.Bundle; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.ToggleButton; import android.telephony.SmsMessage; public class SmsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; if (bundle != null) { //---retrieve the SMS message received--- Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; String str=""; for (int i=0; i&lt;msgs.length; i++){ msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); str += "SMS from " + msgs[i].getOriginatingAddress(); } } } } </code></pre> <p>I know I should use findViewById() to reach the status of the buttons, but I can't directly use it because SmsReceiver isn't extended from Activity. So far, what I tried to use findViewById</p> <p>1- Cast context to Activity</p> <pre><code>try{ tb = (ToggleButton) ((Activity)context).findViewById(R.id.toggleButton3); if(tb.isChecked()) Log.d("sms","SOUND-ON"); else if(!tb.isChecked()) Log.d("sms","SOUND-OFF"); }catch(Exception e){ Log.d("sms","Error " + e); } </code></pre> <p>It gives java.lang.ClassCastException: android.app.ReceiverRestrictedContext</p> <p>2- Use LayoutInflater</p> <pre><code>try{ LayoutInflater mInf = LayoutInflater.from(context); View myView = mInf.inflate(R.layout.activity_favorite_list, null); tb = (ToggleButton) myView.findViewById(R.id.toggleButton3); if(tb.isChecked()) Log.d("sms","SOUND-ON"); else if(!tb.isChecked()) Log.d("sms","SOUND-OFF"); }catch(Exception e){ Log.d("sms","Error" + e); } </code></pre> <p>This is not working too, because it gives only the status of Toggle Button when app is started. Please help, thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload