Broadcast Receivers And Fragments
I have this scenario implemented where I have a navigation drawer with nested fragments that are added to the back stack with tag. Every fragment has the following implemented: @Ov
Solution 1:
My case was to update the textfield in one of the fragments hosted by MainActivity.The simplest solution I found was this:--
In my MainActivity class retrieved the running instance of MainActivtiy.This is my MAinActivity
privatestaticMainActivity mainActivityRunningInstance;
publicstaticMainActivitygetInstace(){
return mainActivityRunningInstance;
}
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainActivityRunningInstance =this;
----------
}
Now in Broadcast reciever's onRecieve method, get that instance and call the update method
@OverridepublicvoidonReceive(Context context, Intent intent) {
if (intent.getAction().matches(Intents.PROVIDER_CHANGED_ACTION)) {
String textValue="the text field value";
// the null check is for, if the activity is not running or in paused state, in my case the update was required onlyif the main activity is active or pausedif(MainActivity.getInstace()!=null)
MainActivity.getInstace().updateUI(textValue);
}
Now for the part where we need to run the update in UIThread,The updateUI method of MainActivity will call the fragments update method.
publicvoidupdateUI(final String str) {
MainActivity.this.runOnUiThread(newRunnable() {
publicvoidrun() {
//use findFragmentById for fragments defined in XML ((SimpleFragment)getSupportFragmentManager().findFragmentByTag(fragmentTag)).updateUI(str);
}
});
}
and the final step is updating the fragment's text field
publicvoidupdateUI(String str){
tv_content.setText(str);
}
and Bingo, its done. I referred post to solve my issue. Hope it help others.
Post a Comment for "Broadcast Receivers And Fragments"