Reputation: 597
I have an OnCLick listener class in my Android app defined as below. I need to access an application-level variable, but the last line in this code generates this compile error: "The method getApplication() is undefined for the type OnClickListenerSelectPresetItem"
How can I access Application variables from this class?
public class OnClickListenerSelectPresetItem implements OnClickListener {
private long glbMealId = ((MyApplication) this.getApplication()).getMealId();
Upvotes: 0
Views: 483
Reputation: 16122
OK. Finally understood what your question is all about.
You wanna reference your implementation of the Application
class.
So either:
Pass an Activity
to the constructor of OnClickListenerSelectPresetItem
as @pdegand59 suggested.
Make MyApplication a singleton, for convenience (this is what I do because I don't like passing Activities): Android Application as Singleton
Upvotes: 0
Reputation: 13029
The error is pretty explicit. this
is the listener object, not the Context executing the listener.
You should use ActivityExecutingListener.this.getApplication()
.
EDIT : If your listener is not an anonymous/inner class, you need to store the Context in the listener instance :
public class OnClickListenerSelectPresetItem implements OnClickListener {
private long glbMealId;
private Activity activity;
public OnClickListenerSelectPresetItem(Activity activity) {
this.activity = activity; // facultative, but you may need it in onClick() ...
this.glbMealId = ((MyApplication) activity.getApplication()).getMealId();
}
...
}
Upvotes: 3
Reputation: 16122
The this operator in your case references OnClickListenerSelectPresetItem
.
Here is an example of what you're trying to do, cut-pasted from one of my projects:
public class PageFragment extends Fragment {
private boolean isVisible( View view )
{
return true; // fake
}
private class OnLikeClickListener implements OnClickListener
{
private boolean isVisible = PageFragment.this.isVisible(); // <------
@Override
public void onClick(View v)
{
// Do whatever
}
}
}
Upvotes: 0