N
N
newdancer2016-02-21 18:38:39
Java
newdancer, 2016-02-21 18:38:39

Error in application must implement onSomeEventListener? What's wrong?

The application crashes with an error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{net.kinomovies.onlinemovielibrary/net.kinomovies.onlinemovielibrary.MainActivity}: java.lang.ClassCastException: [email protected] must implement onSomeEventListener

API class error on this line: throw new ClassCastException(ctx.toString()
before this class is called on this line: api = new API(getActivity());
The classes are described below. What's wrong?
public class MovieFragment extends Fragment implements API.APIS
{
    public static final String ARG_CATEG_NUMBER = "cat_number";
    ArrayList<Cinema> cinemas = new ArrayList<Cinema>();
    CinemaAdapter cinemaAdapter;

    // класс для retrofit
    API api;
    int numCat;
    String title="";
    int kinopoisk_id=0;

    public MovieFragment() {
        // пустой конструктор
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
    {
        // подключаем API
        api = new API(getActivity());

        View rootView = inflater.inflate(R.layout.fragment_categ, container, false);
        numCat = getArguments().getInt(ARG_CATEG_NUMBER);
        Log.d("myLogs", "numCat=" + numCat);

        // создаем адаптер
        api.getCinema(numCat, title, kinopoisk_id);
        cinemaAdapter = new CinemaAdapter(getActivity(), cinemas);

        // настраиваем список
        ListView lvMain = (ListView) rootView.findViewById(R.id.lvMain);
        lvMain.setAdapter(cinemaAdapter);

        String categTitle = getResources().getStringArray(R.array.categories_array)[numCat];

        getActivity().setTitle(categTitle);
        return rootView;
    }

    @Override
    public void getData()
    {
        cinemaAdapter.notifyDataSetChanged();
    }
}

API class
public class API
{
    private static final String SOURCE = "http://moonwalk.cc/api";
    private final CinemaService mService;
    String api_token="тут токен";

    final String TAG = "myLogs";
    Context ctx;

    ArrayList<Cinema> cinemas = new ArrayList<Cinema>();

    public interface CinemaService {
        @GET("/movies_updates.json")
        Call<CinemaData> getCinemas(@Query("api_token") String api_token);
    }

    public interface APIS
    {
        public void getData();
    }
    APIS apis;

    public API(Context ctx) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(SOURCE)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        mService = retrofit.create(CinemaService.class);
        try {
            apis = (APIS) ctx;
        } catch (ClassCastException e) {
            throw new ClassCastException(ctx.toString()
                    + " must implement onSomeEventListener");
        }

        this.ctx = ctx;
    }

    public boolean getCinema(final int numCat, final String title, final int kinopoisk_id)
    {
        mService.getCinemas(api_token).enqueue(new Callback<CinemaData>() {
            @Override
            public void onResponse(Response<CinemaData> response, Retrofit retrofit)
            {
                cinemas.add(new Cinema(response.body().responseData.rusTitle));
                apis.getData();
            }

            @Override
            public void onFailure(Throwable t) {
                Log.d("myLogs", "Failed!!!");
            }
        });
        return true;
    }
}

class CinemaData {
    ResponseData responseData;
}

class ResponseData {
    String rusTitle;
    String match;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
razer89, 2016-02-21
@newdancer

Judging by the logs, your MainActivity must implement the APIS interface, which is most likely not the case. Add to MainActivity implements APIS, and implement the methods of this interface

D
Denis Zagaevsky, 2016-02-21
@zagayevskiy

You push getActivity () as a context into your API. And you check it

try {
            apis = (APIS) ctx;
        } catch (ClassCastException e) {
            throw new ClassCastException(ctx.toString()
                    + " must implement onSomeEventListener");
        }

So the activity must implement this interface. It would be better to transfer it to a separate variable. And this check is not kosher, it's better to write
if (!ctx instanceof SomeMyInterface) {
    throw new IllegalStateException("ctx must imlement " +  SomeMyInterface.class.getName());
} 
myInterfaceVar = (SomeMyInterface) ctx;

Do not sin with copy-paste, at least read the code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question