Search code examples
javaandroidinterface

Calling interface cause NullPointerEx


I'm trying to pass my respond to mainActivity via an interface but when I call or initialize it to give it the response, it says that the interface which is packageSender is null. my response is not null, the interface is. why is that and what is the solution?

public  class ApiService {
    RetrofitApi retrofitApi;
    packageSender packageSender;

    public ApiService(){
        Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(url).build();
        retrofitApi = retrofit.create(RetrofitApi.class);
        retrofitApi.getStudent().enqueue(new Callback<List<Student>>() {
            @Override
            public void onResponse(Call<List<Student>> call, Response<List<Student>> response) {
                getStudentPack(response.body());
            }

            @Override
            public void onFailure(Call<List<Student>> call, Throwable t) {
            }
        });
    }
    public interface packageSender{
        void packageItself(List<Student> pack);
    }
    private void getStudentPack (List<Student> students){
            packageSender.packageItself(students);
    }
}

Solution

  • There is at least two problems with your code:

    public  class ApiService {
        RetrofitApi retrofitApi;
        packageSender packageSender;
    

    first you do this, you declared a new class, and 2 variables inside. But you never initialized packageSender variable, therefore packageSnder is null

    later on you do retrofitApi = retrofit.create(RetrofitApi.class); which assign a new value to retrofitApi, but you never assign a value to packageSender.

    To fix your problem, you would have to create an instance of a class that implements your interface (careful! you can't instantiate an interface, so you'd need a class that implements the interface) and then assign it to your variable in the constructor