How can I update the main thread from a BroadCastReceiver. I have a BroadCastReceiver which receives a string and I need to set the text for a textview on my MainActivity, when I do findViewById(R.id.textView);
on the onReceive method it returns null.
Here is my onCreate for the MainActivity.
public class MainActivity extends Activity {
......
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter broadcastFilter = new IntentFilter(ResponseReceiver.LOCAL_ACTION);
receiver = new ResponseReceiver();
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.registerReceiver(receiver, broadcastFilter);
Intent msgIntent = new Intent(MainActivity.this, IntentService.class);
msgIntent.putExtra(StockDataIntentService.PARAM_IN_MSG, getResources().getString(R.string.url));
startService(msgIntent);
}
public class ResponseReceiver extends BroadcastReceiver {
public static final String LOCAL_ACTION = "com.mypackage.ALL_DONE";
private Handler handler;
@Override
public void onReceive(Context context, Intent intent) {
String text =intent.getStringExtra(IntentService.PARAM_OUT_MSG);
TextView txtError = (TextView) findViewById(R.id.error);
}
}
OP for this question was having exact same issue, the accepted answer explains to use a handler etc.. But reading the comments on the answer explain the BroadastReceiver runs on the main thread so there is no reason to use a handler. How come I am unable to set the text on the text view ?