java - Calling a function from MainActivity, from a class which is in a different module -


i have single activity called mainactivity. has function has called class in different module

public class mainactivity extends activity {   @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_main);  }   @override       public boolean oncreateoptionsmenu(menu menu) {     // inflate menu; adds items action bar if present.     getmenuinflater().inflate(r.menu.menu_main, menu);     return true; }   public void tag_proc(string s1) {      system.out.println("working guess"+s1)  } } 

this function has called class module

public class newcls {        mainacitivity mact= new mainactivity();        public void dothis()        {   string s="new";        mact.tag_proc(s);                }   } 

this cannnot done because in different modules. best , easy solution this. if interface solution, how best use it

not clear want achieve never this:

mainacitivity mact= new mainactivity(); 

you create activities through intents, not yourself.

if want tightly coupled module pass activity in constructor e.g.

public newcls(mainactivity activity) {     myactivityreference = activity }  public void dothis() {     ...     myactivityreference.tag_proc(s); } 

it best if extract interface , use instead of activity class itself, simplicity showed trivial way.

if want more loosly coupled communication can use local broadcasts. register receiver in activity , send broadcast newcls this

public void dothis() {   intent intent = new intent("custom-event-name");   intent.putextra("mystring", "this message!");   localbroadcastmanager.getinstance(context).sendbroadcast(intent); } 

and in activity

@override public void oncreate(bundle savedinstancestate) {    ...    // register receive messages. registering observer (mmessagereceiver) receive intents actions named "custom-event-name".   localbroadcastmanager.getinstance(this).registerreceiver(mmessagereceiver,       new intentfilter("custom-event-name")); }  // our handler received intents. called whenever intent action named "custom-event-name" broadcasted. private broadcastreceiver mmessagereceiver = new broadcastreceiver() {   @override   public void onreceive(context context, intent intent) {     string s1= intent.getstringextra("mystring");     tag_proc(s1);   } };  @override protected void ondestroy() {   // unregister since activity closed.      localbroadcastmanager.getinstance(this).unregisterreceiver(mmessagereceiver);       super.ondestroy(); } 

see more on broadcasts in question.


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -