I have a fragment, which is being used inside a MainActivity, actually it is used inside a ViewPager in a MainActivity.
public class Myfragment extends Fragment implements MySingleton.ResponseInterface{
public static Myfragment newInstance() {
final Myfragment mf = new Myfragment();
return mf;
}
public Myfragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
//.....
final MySingleton mysingleton = MySingleton.getInstance(getContext());
//I have a button in the fragment that I use like this
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mysingleton.getSomeResponse();
}
});
}
@Override
public void onResponseGiven(String response) {
Log.d("response", response);
}
}
I have a Singleton class to be used for different actions, the singleton includes an interface:
public class MySingleton{
private static MySingleton mInstance;
private static Context mContext;
public ResponseInterface responseInterface;
private MySingleton(Context context){
mContext = context;
this.responseInterface = (ResponseInterface) context;
}
public static synchronized MySingleton getInstance(Context context){
if(mInstance == null){
mInstance = new MySingleton(context);
}
return mInstance;
}
public void getSomeResponse(){
responseInterface.onResponseGiven("send response");
}
public interface ResponseInterface{
void onResponseGiven(String response);
}
}
Why do I get ClassCastException
telling that MainActivity cannot be casted to MySingleton.ResponseInterface??