java - Sending data from Activity to Fragment from internet -
i have class contains 3 fragment
data needs gathered same url. run nested async class(in activity) data url , store data in bundle each fragment like.
bundle bundle = new bundle(); bundle.putstring("edttext", json.tostring()); infofragment fragobj = new infofragment(); fragobj.setarguments(bundle);
before calling async class in fragment , working fine,but added 2 more fragments reduce number of url requests, calling async class activity class , distribute data 3 fragment class.
issue:fragment called before bundle set asynchronously , showing null bundle in fragment.
you can broadcast intent parent activity after response in onpostexeceute() of asynctask
@override protected void onpostexecute(object o) { super.onpostexecute(o); intent intent = new intent("key_to_identify_the_broadcast"); bundle bundle = new bundle(); bundle.putstring("edttext", json.tostring()); intent.putextra("bundle_key_for_intent", bundle); context.sendbroadcast(intent); }
and can receive bundle in fragment using broadcastreceiver class
private final broadcastreceiver mhandlemessagereceiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { bundle bundle = intent.getextras().getbundle("bundle_key_for_intent"); if(bundle!=null){ string edttext = bundle.getstring("edttext"); } //you can call of methods using bundle use case } };
in oncreateview() of fragment need register broadcast receiver first otherwise broadcast receiver not triggered
intentfilter filter = new intentfilter("key_to_identify_the_broadcast"); getactivity().getapplicationcontext(). registerreceiver(mhandlemessagereceiver, filter);
finally can unregister receiver avoid exceptions
@override public void ondestroy() { try { getactivity().getapplicationcontext(). unregisterreceiver(mhandlemessagereceiver); } catch (exception e) { log.e("unregister error", "> " + e.getmessage()); } super.ondestroy(); }
you can create separate broadcast receivers in of fragments , use same broadcast broadcast data of fragments. can use different keys different fragments , broadcast using particular key particular fragment.
Comments
Post a Comment