MAOL MAOL - 13 days ago 5
Android Question

How to wait until Callback has data?

I'm trying to use Retrofit and OkHttp to make request to a server. I have the next class "AutomaticRequest.java" which has a request to get videos from a server.

public class AutomaticRequest {

public void getVideos(final AutomaticCallback callback){

MediaproApiInterface service = ApiClient.getClient();
Call<List<AutomaticVideo>> call = service.getAllVideos();
call.enqueue(new Callback<List<AutomaticVideo>>() {

@Override
public void onResponse(Call<List<AutomaticVideo>> call, Response<List<AutomaticVideo>> response) {
List<AutomaticVideo> automaticVideoList = response.body();
callback.onSuccessGettingVideos(automaticVideoList);

}

@Override
public void onFailure(Call<List<AutomaticVideo>> call, Throwable t) {
callback.onError();
}
});

}
}


I've created the next class "AutomaticCallback.java" to retrieve data.

public interface AutomaticCallback {
void onSuccessGettingVideos(List<AutomaticVideo> automaticVideoList);
void onError();
}


I'm calling the request from a fragment like the next way:

public class AllVideosFragment extends Fragment {

...
AutomaticCallback callback;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_allvideos, container, false);

new AutomaticRequest().getVideos(callback);

return view;
}

...

}


How I can wait until the callback has data to update the UI?? Thank you.

Answer

Just implement the AutomaticCallback interface on your fragment like:

    public class AllVideosFragment extends Fragment implements AutomaticCallback {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_allvideos, container, false);

        new AutomaticRequest().getVideos(this);

        return view;
    }

    @Override
    void onSuccessGettingVideos(List<AutomaticVideo> automaticVideoList){
       // use your data here
    }

    @Override
    void onError(){
      // handle the error
    }
}
Comments