Search code examples
androidandroid-fragmentsandroid-servicemediabrowserservicecompat

Communication problems between fragment and a server


I have a fragmment that I would like to communicate with a server, but the problems is that i always get null pointer

I have this in my fragment onCreateView:

public class BrowseFragment extends Fragment implements View.OnClickListener{

private MusicService mMusicService;


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



    mMusicService = new MusicService(this);
             mMusicService.setCallback(new MusicService.Callback() {


                                @Override
                                public void onPlayPause(String state) {
                                    //Do something
                                }
                            });

}
}

This is my service:

 public class MusicService extends MediaBrowserServiceCompat {


public interface Callback {
        public void onPlayPause(String state);
    }

    public void setCallback(Callback callback) {
        this.mCallback = callback;
    }





private void PauseRequest() {
        mPlayback.pause();
        //if (mCallback != null) {
            mCallback.onPlayPause("PAUSE");
        //}
}

}

I´m getting this FATAL EXCEPTION: main

Process: com.geobytenet.mediaplayer, PID: 3262
java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.android.mediabrowserservice.MusicService$Callback.onPlayPause(java.lang.String)' on a null object reference

I hope you can help me


Solution

  • In MusicService, I added this method

        public void pausePlay() {
            PauseRequest();
        }
    

    Then in BrowseFragment, in onCreateView()

        Button button = (Button)rootView.findViewById(R.id.button_play_pause);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mMusicService.pausePlay();
            }
        });