I have one activity and 2 fragment.
I want when in activity fire listener.receivePreview(obj) then
execute : OneFragment -> receivePreview .
execute : TwoFragment -> receivePreview .
public class MainAct extends AppCompatActivity {
public interface OnReceiveListener {
// This can be any number of events to be sent to the activity
void receivePreview(Object... obj);
}
private OnReceiveListener listener;
}
public class OneFragment extends Fragment implements OnReceiveListener{
#Override
public void receivePreview(Object... obj) {
}
}
public class TwoFragment extends Fragment implements OnReceiveListener{
#Override
public void receivePreview(Object... obj) {
}
}
I think you can use Observer Pattern that is a good practice in you situation.
As described by GoF:
"Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically".
Read more at http://www.java2blog.com/2013/02/observer-design-pattern-in-java.html#TLio7G2ruqxvfZUR.99
In your situation you have such relation (one-to-many) and when an event occurred in the activity you want to aware that two fragment.
Fragments are implement observer class and your activity has the role of subject as illustrate in above figure.
I hope this could help you to implements your code in a very nice way.
some tutorial can be find in the following links :
https://dzone.com/articles/observer-pattern-java
http://www.tutorialspoint.com/design_pattern/observer_pattern.htm
Edit: in the given situation:
public interface OnReceiveListener { // this is your observer interface !
// This can be any number of events to be sent to the activity
void receivePreview(Object... obj);
}
Fragment are in correct definition with this design pattern so I do not change their code :
public class OneFragment extends Fragment implements OnReceiveListener{
#Override
public void receivePreview(Object... obj) {
}
}
public class TwoFragment extends Fragment implements OnReceiveListener{
#Override
public void receivePreview(Object... obj) {
}
you need to have references to the fragments in the activity (as observer).
ArrayList< OnReceiveListener > observers = new ArrayList< OnReceiveListener>();
indeed an observer can subscribe or register itself to a subject ( fragment hold a reference to the activity (better to use singleton pattern ! :D). like this :
public class MainAct extends AppCompatActivity {
private static MainAct instance;
public static MainAct getInstance() {
if(instance != null)
return instance;
}
// I think it is better to create the instance variable in the onCreate() method of the MainAct activity
onCreate(...)
{
.
.
.
instance = this;
...
}
public void registerObserver(OnReceiveListener observer){
observers.add(observer)
}
/* To avoid memory leaks, remember to unregister receivers when no longer observing */
public void unregisterObserver(OnReceiveListener observer) {
observers.remove(observer);
}
notifyObservers(){
// call this method in the listener you want
for( Observer obser : observers)
obser. receivePreview(param )
}
...
//in fragment initialization:
MainAct.getInstance().registerObserver(this)
I use answer Sirvan Paraste.It seems that this useful solution.
public class MainAct extends AppCompatActivity {
static List<OnReceiveListener> onReceiveList = new ArrayList<OnReceiveListener>();
public void attachOnReceiveListener(OnReceiveListener listener) {
if (!onReceiveList.contains(listener)) {
onReceiveList.add(listener);
}
}
public interface OnReceiveListener {
// This can be any number of events to be sent to the activity
void receivePreview(Object... obj);
}
public onReceivePreview(Object... obj) {
for (OnReceiveListener listener : onReceiveList) {
listener.receivePreview(obj);
}
}
}
public class OneFragment extends Fragment implements OnReceiveListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MainAct mainAct = new MainAct();
mainAct.attachOnReceiveListener(this);
}
#Override
public void receivePreview(Object... obj) {
}
}
public class TwoFragment extends Fragment implements OnReceiveListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MainAct mainAct = new MainAct();
mainAct.attachOnReceiveListener(this);
}
#Override
public void receivePreview(Object... obj) {
}
}
Try to create one function in each fragment which returns the interface instance
public OnReceiveListener getListener() {
mListener = this;
return mListener
}
and in your activity when you call the method write following code
fragmentInstance.getListener().receivePreview();
Related
I have troubles on calling the method update from MainActivity class in a the MSG0100 non-activity class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void update(boolean msg100Preselection){
if(msg100Preselection){
mExpandableListViewAdapter.setSelectedChild(-1);
mExpandableListViewAdapter.notifyDataSetChanged();
}
}
}
And this is my class where i want to call the update method of Mainactivity.
public class MSG0100{
boolean msg100Preselection=false;
pulic void onUpdate(){
msg100Preselection=true;
// Want to call my update method here
MainActivity activity= new MainActivity();
activity.update(msg100Preselection); //<-------- Using mainactiviy object crashes my app.
}
}
What you want is impossible as you dont have a pointer to your main activity.
The following statement is invalid.
MainActivity activity= new MainActivity();
You are not allowed to use the new operator to create an activity. That should be done using an intent.
There are several things you could do:
Move your update method in another class
OR
declare your update method as static and use it like this:
MainActivity.update(msg100Preselection);
Try using a callbackListener :-
In your MSG0100 class
public class MSG0100 {
boolean msg100Preselection = false;
private static OnUpdateListener mListener;
public static setListener(OnUpdateListener mListener) {
this.mListener = mListener;
}
public void onUpdate() {
msg100Preselection = true;
if (mListener != null)
mListener.onUpdate(msg100Preselection);
}
public interface OnUpdateListener()
{
void onUpdate ( boolean msg100Preselection);
}
}
In your MainActivity-
public class MainActivity extends AppCompatActivity, OnUpdateListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MSG0100.setListener(this)
}
#Override
public void onUpdate(boolean msg100Preselection) {
if (msg100Preselection) {
mExpandableListViewAdapter.setSelectedChild(-1);
mExpandableListViewAdapter.notifyDataSetChanged();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
MSG0100.setListener(null)
}
}
This way you won't have any memory leaks or crashes due to Activity being killed.
My project have 1 activity class, 1 interface class and 2 classes. One class is extends with AsyncTask.
Activity Class
public class ActivityClass extends AppCompatActivity implements TaskListener {
TaskListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Call asyncTask class
Server myServer = new Server(listener);
myServer.execute(request);
}
#Override
public void taskComplete(boolean status) {
//Task complete
}
}
Interface Class
public interface TaskListener {
public void taskComplete(boolean status);
}
AsyncTask Class
public class Server extends AsyncTask<JSONObject, Void, Void> {
TaskListener listener;
public Server(TaskListener l) {
this.listener = l;
}
#Override
protected Void doInBackground(JSONObject... params) {
...........
}
#Override
protected void onPostExecute(Void result) {
listener.taskComplete(success);
}
}
Other Class
public class Operation extends TaskListener {
}
I've got an error in Other Class (No interface expected here). I'm confused how can I implement Interface class in the both class.
public class Operation extends TaskListener {}
Because extends expects a class, not an interface. Interface should be used with implements. Change to:
public class Operation implements TaskListener {}
I want to convert my project according to MVP structure, & I had done it but it violate the MVP design, as it holds the activity instance in the presenter layer.
So, I just wanted to know how can I convert this project into pure MVP. Here Validation class is recursive and validate many fields & for here it is just for signup, and I had put the Validate method into separate thread.
This is my MVP interface
import android.app.Activity;
public class IMVP_Login {
/**
* View mandatory methods. Available to Presenter
* Presenter -> View
*/
public interface RequiredViewOps {
void showToast(String msg);
}
/**
* Operations offered from Presenter to View
* View -> Presenter
*/
public interface PresenterOps{
void submit(Activity activity);
}
}
This is my presenter with thread and containing the activity instance, which is against the design pattern of MVP, the code is as follows
import android.app.Activity;
import java.lang.ref.WeakReference;
import cp.utility.CustomException;
import cp.utility.Validation;
public class PresenterLogin implements Runnable,IMVP_Login.PresenterOps
{
private WeakReference<IMVP_Login.RequiredViewOps> mView;
// this is against the architectural law of MVP
private WeakReference<Activity> activity;
public PresenterLogin(IMVP_Login.RequiredViewOps mView) {
this.mView = new WeakReference<>(mView);
}
#Override
public void run() {
try
{
Validation.validate(activity.get());
}catch (CustomException e)
{
mView.get().showToast(e.getMessage());
}
}
//how should i do this with MVP PATTERN,as it is holding the activity instance
#Override
public void submit(Activity activity) {
this.activity=new WeakReference<>(activity);
Thread validationThread = new Thread(this,"Validation");
validationThread.start();
}
}
This is my activity,
public class Login extends AppCompatActivity implements View.OnClickListener,IMVP_Login.RequiredViewOps
{
private TextInputEditText edPhone,edCountrycode,edPassword;
private IMVP_Login.PresenterOps presenterLogin;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signin);
initialize();
}
private void initialize()
{
presenterLogin= new PresenterLogin(this);
Button btSignIn=GeneralFunction.findViewByIdAndCast(this,R.id.btnSignIn);
btSignIn.setOnClickListener(this);
edCountrycode = GeneralFunction.findViewByIdAndCast(this, R.id.etCode);
edPhone = GeneralFunction.findViewByIdAndCast(this, R.id.etPhone);
edPassword = GeneralFunction.findViewByIdAndCast(this, R.id.etPassword);
edPassword.setTypeface(Typekit.getInstance().get(getString(R.string.str_regular)));
edPassword.setTransformationMethod(new PasswordTransformationMethod());
}
#Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.btnSignIn:
presenterLogin.submit(this);
break;
}
}
#Override
public void showToast(String msg) {
//show toast
}
}
This is the validation class depending on tag of editext,
public class Validation {
public static boolean validateFields(final ViewGroup parentView) throws CustomException
{
for (int i = 0; i < parentView.getChildCount(); i++)
{
if (parentView.getChildAt(i) instanceof ViewGroup) {
if ((parentView.getChildAt(i)).getVisibility() == View.VISIBLE)
validateFields((ViewGroup) parentView.getChildAt(i));
}
else if((parentView.getChildAt(i) instanceof TextView) && ((parentView.getChildAt(i)).getVisibility() == View.VISIBLE))
{
TextView editText = (TextView) parentView.getChildAt(i);
if(null!=editText.getTag())
{
String type = editText.getTag().toString().toLowerCase();
String text=GeneralFunction.getTextFromView(editText);
//validation depending on tag
}
}
}
return true;
}
public static boolean validate(Activity activity) {
final ViewGroup viewGroup = (ViewGroup) activity.findViewById(android.R.id.content);
return validateFields(viewGroup);
}
}
Let me start by saying that there are many different ways of doing MVP, each of them valid in their own right. The important things to keep in mind are:
The View should not know about the model, it doesn't care at all where its data is coming from.
The Presenter should not know about Android. You should be able to run your Presenter class entirely on the JVM.
Your Activity/Fragment/ViewGroup should implement the View interface which is how the Presenter communicates with them.
Why do we do this?
Separation of concerns.
You can change the network library you use in your Model and the View/Presenter should just work still. You could switch your View from a horizontal ViewPager to a vertical RecyclerView and the Presenter/Model equally wouldn't care.
Testing.
We can mock our Presenter and unit test the View or Model. Mock the View & Model and unit test the Presenter.
As long as the implementation of MVP that you are using allows the above then in my mind it is valid.
Onto your specific problem. I would set it up something like this:
View:
public interface LoginView {
Map<String,String> getLoginFields();
}
Activity:
public class LoginActivity extends AppCompatActivity implements LoginView {
private EditText emailView;
private EditText phoneView;
private EditText passwordView;
private Button loginView;
private LoginPresenter presenter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
presenter = new LoginPresenter();
presenter.bindView(this);
emailView = findViewById(R.id.login_email);
phoneView = findViewById(R.id.login_phone);
passwordView = findViewById(R.id.login_password);
loginView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
presenter.login();
}
});
}
#Override
protected void onDestroy() {
presenter.unbindView();
super.onDestroy();
}
#Override
public Map<String, String> getLoginFields() {
Map<String, String> fields = new HashMap<>();
fields.put(emailView.getTag().toString(), emailView.getText().toString());
fields.put(phoneView.getTag().toString(), phoneView.getText().toString());
fields.put(passwordView.getTag().toString(), passwordView.getText().toString());
return fields;
}
}
You may wish to do something fancy with the getLoginFields method and loop through your container. Even if you had 100 fields though it shouldn't require offloading onto another thread. I'd be a very upset user if I had to fill out 100 fields...
Presenter:
public class LoginPresenter {
private LoginView view;
private LoginValidator validator;
public void bindView(LoginView view) {
this.view = view;
}
public void unbindView() {
view = null;
}
public void login() {
validator = new LoginValidator();
Map<String, String> fields = view.getLoginFields();
boolean isValid = validator.validate(fields);
}
}
Validator:
public class LoginValidator {
public boolean validate(Map<String, String> fields) {
//validation depending on tag
return true;
}
}
Threading
If the need does arise to process something on another thread in the Activity then you have several approaches you could take:
Pass a listener to the getLoginFields() method which gets called when the work is done.
Expose another method in the Presenter, something like onLoginFieldsProcessed which would get called once the work is done.
Have getLoginFields() return Observable (RxJava) or Future.
I would personally probably use RxJava, especially if I was already using it in the app.
The main reason why there is separate presenter class added in this MVP framework ( especially in android ) is to remove the OutOfMemory or if by chance the activity fails the presenter calls is not affected i.e why there is MVP approach followed instead of MV framework.
Consider the below example that is from below link :-
public class MainActivity extends Activity {
public static final String DEFAULT_NAME = "Chuck Norris";
private ArrayAdapter<ServerAPI.Item> adapter;
private Subscription subscription;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(adapter = new ArrayAdapter<>(this, R.layout.item));
requestItems(DEFAULT_NAME);
}
#Override
protected void onDestroy() {
super.onDestroy();
unsubscribe();
}
public void requestItems(String name) {
unsubscribe();
subscription = App.getServerAPI()
.getItems(name.split("\\s+")[0], name.split("\\s+")[1])
.delay(1, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<ServerAPI.Response>() {
#Override
public void call(ServerAPI.Response response) {
onItemsNext(response.items);
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable error) {
onItemsError(error);
}
});
}
public void onItemsNext(ServerAPI.Item[] items) {
adapter.clear();
adapter.addAll(items);
}
public void onItemsError(Throwable throwable) {
Toast.makeText(this, throwable.getMessage(), Toast.LENGTH_LONG).show();
}
private void unsubscribe() {
if (subscription != null) {
subscription.unsubscribe();
subscription = null;
}
}
}
In the above example the activity failure causes the presenter layer to stop working .Similarly ,if there is any object associated with this activity class ( View ) will be affected .
Referencing by static will make the activity die out while there is a crash but the presenter class will not be affected.( Please refer to below code for MVP ).
public class MainPresenter {
public static final String DEFAULT_NAME = "Chuck Norris";
private ServerAPI.Item[] items;
private Throwable error;
private MainActivity view;
public MainPresenter() {
App.getServerAPI()
.getItems(DEFAULT_NAME.split("\\s+")[0], DEFAULT_NAME.split("\\s+")[1])
.delay(1, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<ServerAPI.Response>() {
#Override
public void call(ServerAPI.Response response) {
items = response.items;
publish();
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
error = throwable;
publish();
}
});
}
public void onTakeView(MainActivity view) {
this.view = view;
publish();
}
private void publish() {
if (view != null) {
if (items != null)
view.onItemsNext(items);
else if (error != null)
view.onItemsError(error);
}
}
}
public class MainActivity extends Activity {
private ArrayAdapter<ServerAPI.Item> adapter;
private static MainPresenter presenter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(adapter = new ArrayAdapter<>(this, R.layout.item));
if (presenter == null)
presenter = new MainPresenter();
presenter.onTakeView(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
presenter.onTakeView(null);
if (!isChangingConfigurations())
presenter = null;
}
public void onItemsNext(ServerAPI.Item[] items) {
adapter.clear();
adapter.addAll(items);
}
public void onItemsError(Throwable throwable) {
Toast.makeText(this, throwable.getMessage(), Toast.LENGTH_LONG).show();
}
}
MainActivity creates MainPresenter and keeps it outside of reach of onCreate/onDestroy cycle. MainActivity uses a static variable to reference MainPresenter, so every time a process restarts due to out-of-memory event, MainActivity should check if the presenter is still here and create it if needed.( As stated in the doc ).
Hope this helps :)
I have service, which gets data from API and sends this data to BroadcastReceiver class. Also, I create interface OnReceiveListener, which used in Activity. Look at the code here:
Activity:
public class StartActivity extends AppCompatActivity
implements MyBroadcastReceiver.OnReceiveListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
MyBroadcastReceiver receiver = new MyBroadcastReceiver();
receiver.setOnReceiveListener(this);
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
new IntentFilter(MyBroadcastReceiver.START));
...
}
#Override
public void onReceive(Intent intent) {
// Do smth here
}
}
MyBroadcastReceiver:
public class MyBroadcastReceiver extends BroadcastReceiver {
public static final String START = "com.example.myapp.START";
public static final String GET_LINKS = "com.example.myapp.GET_LINKS";
private OnReceiveListener onReceiveListener = null;
public interface OnReceiveListener {
void onReceive(Intent intent);
}
public void setOnReceiveListener(Context context) {
this.onReceiveListener = (OnReceiveListener) context;
}
#Override
public void onReceive(Context context, Intent intent) {
if(onReceiveListener != null) {
onReceiveListener.onReceive(intent);
}
}
}
Service isn't important on this question.
---- Question ----
So, what's problem: I want to use this receiver in fragment, but when it sets context - I get exception "enable to cast". What I should to do on this case?
Here is my code in fragment:
public class MainFragment extends Fragment
implements MyBroadcastReceiver.OnReceiveListener {
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
myBroadcastReceiver.setOnReceiveListener(getContext());
LocalBroadcastManager.getInstance(getContext()).registerReceiver(myBroadcastReceiver,
new IntentFilter(MyBroadcastReceiver.GET_LINKS));
}
#Override
public void onReceive(Intent intent) {
// Do smth here
}
}
Your MainFragment class implements your OnReceiveListener interface, not its Context as returned by getContext(). Instead of passing a Context object into setOnReceiveListener(), try directly passing an OnReceiveListener instance. Then your fragment and activity can both call setOnReceiveListener(this).
you don't need to dynamically register the receiver. i believe you must have registered it in manifest using <receiver> tag.
this is not required:
LocalBroadcastManager.getInstance(getContext()).registerReceiver(myBroadcastReceiver,
new IntentFilter(MyBroadcastReceiver.GET_LINKS));
and about callback registering listener, instead of using getContext() use MainFragment.this like this:
myBroadcastReceiver.setOnReceiveListener(MainFragment.this);
After searching for hours for the appropriate way to implement such a solution to this problem, I've found a way finally. It is based on RussHWolf's answer. The complete solution with code is below:
In this way, a setListener() method is exposed so that Fragment or Activity can set the listener by sending an instance of IStatusChangeListener.
public class StatusChangeReceiver extends BroadcastReceiver {
private IStatusChangeListener listener;
public void setListener(IStatusChangeListener listener) {
this.listener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
if (NetworkUtil.isNetworkConnected()) {
listener.onConnected();
} else {
listener.onDisconnected();
}
}
}
This is the interface:
public interface IStatusChangeListener {
void onConnected(String status);
void onDisonnected(String status);
}
Now, it is required to have an instance of IStatusChangeListener interface instead of implementing the IStatusChangeListener interface. And then, pass this instance of IStatusChangeListener to setListener() method.
public class MainFragment extends Fragment { //Not implementing the interface
private IStatusChangeListener listener = new IStatusChangeListener() {
#Override
void onConnected(String status) {
//some log here
}
#Override
void onDisonnected(String status) {
//some log here
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
StatusChangeReceiver r = new StatusChangeReceiver();
r.setListener(listener); // pass the IStatusChangeListener instance
LocalBroadcastManager.getInstance(getContext()).registerReceiver(r, new IntentFilter("connectionStatus"));
}
}
Note: Always use LocalBroadcastManager if you register BroadcastReceiver from Fragment.
Just started programming and I'm coding my first app. I've been wrecking my brain over this for long enough. I picked this up from tutorial where a listener is implemented in a ListFragment and the event listener is in a FragmentActivity that hosts the ListFragment. Here is how it is in the example (showing only the relevant part):
MyList class:
public class MyList extends ListFragment{
OnSomeItemSelectedListener mCallback;
public interface OnSomeItemSelectedListener {
public void onSomeItemSelectedListener(int position, long id);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mCallback = (OnSomeItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnSomeItemSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
mCallback.onSomeItemSelectedListener(position, id);
}
}
MainActivity class:
public class MainActivity extends FragmentActivity implements
MyList.OnSomeItemSelectedListener{
#Override
public void onSomeItemSelectedListener(int position, long id) {
//some stuff done here when clicked on a item from the listfragment
}
}
The above works flawlessly.
I'm trying to implement this in an application class to notify the event listener (a FragmentActivity) when an AsyncTask has finished. This is what I did in in the application class:
MyApplication class:
public class MyApplication extends Application {
OnFetchCompleteListener mCallback;
public interface OnFetchCompleteListener {
public void onFetchCompleteListener();
}
public synchronized void fetchUpdates() {
String[] mURLs = getURLs();
new DownloadDataAsyncTask().execute(mURLs[0], mURLs[1]);
}
private class DownloadDataAsyncTask extends
AsyncTask<String, Void, JSONObject[]> {
#Override
protected JSONObject[] doInBackground(String... params) {
//Some stuff
return mJSON;
}
#Override
protected void onPostExecute(JSONObject[] result) {
// Informing listeners on fetchData complete
mCallback.onFetchCompleteListener();
}
}
}
How do I instantiate the mCallback in the application class? Without this,
mCallback = (OnSomeItemSelectedListener) activity;
I get a null pointer exception from the application class.
Many thanks
I think you can instantiate mCallback from the Activity instead of from the Application.
In your activity's onCreate() or onResume() method, you can write:
MyApplication myApplication = getApplication();
myApplicaton.mCallback = this;
but make sure your activity have implemented OnFetchCompleteListener (I don't why you typed OnSomeItemSelectedListener in the last piece of code.)