I have an OnItemClickListener implementation defined that I use in several Activities and Fragments throughout my application. I’m currently passing the Activity in the constructor, so I can call startActivity without getting an error. I wasn’t sure if this is the appropriate approach.
Is there anything I am doing wrong?
public class EventSelectedListener implements AdapterView.OnItemClickListener {
private Activity mActivity;
private Context mContext;
public EventSelectedListener(Activity activity) {
mActivity = activity;
mContext = mActivity.getApplicationContext();
}
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent intent = new Intent();
intent.setClass(mContext, MediaPlayerActivity.class);
mActivity.startActivity(intent);
}
}
Application’s context and Activity’s context are not the same thing. In your code you are supposed to use Activity’s context.
Change this:
To this:
Or
Alternatively, you dont even need to bother about keeping a separate context object since your mActivity is already having reference to context. So, simply use mActivity where ever you need to refer to context: