I might be missing the concepts of interfaces because this for some reason seems to elude me. Here is my scenario:
Desired Outcome
I would like a non-fragment / non-activity Java class Routines.java
to trigger a method inside FragmentA
when background threads inside Routines.java
are complete.
Current Behavior
I currently communicate to FragmentA
from inside Routines.java
by broadcasting an intent that FragmentA
has registered and is listening for. Although this solution works I can't help but feel that it is not the correct way of doing this.
Questions
I would like to know if it's possible to implement an interface so that I can get rid of the broadcast intents or if in general there is a better way to communicate from non-fragment/activity classes to fragments/activities.
The solution for implementing interfaces from a fragment to activity is not what I am searching for as I already know how to do that but I can't seem to get it working if one side of the communication is not an activity or fragment.
What I've Tried
//in Routines.java
public class Routines implements FragmentA.OnRoutineFinishedListener
public void finished(int position){
...
}
//in FragmentA
public interface OnRoutineFinishedListener {
public void finished(int position);
}
My main issue is that I'm not sure exactly how to call the methods when I can't use the typical approach of using onAttach(Activity activity){ ... set up callback here by casting activity as the interface}
approach like this:
public void onAttach(Activity activity){
super.onAttach(activity);
try {
mCallback = (SomeFragment.SomeListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement SomeListener");
}
}
When it's fragment to activity then the above code makes mCallback
available to me so that I can freely call implementing methods but I don't have that luxury because I'm trying to get a non-fragment to trigger a function inside a fragment.
Always the issue is how to actually trigger the condition where Routines
finally triggers the finished
method inside FragmentA
. I would greatly appreciate some help in understanding how to accomplish this.