Communication problems between fragment and a server

110 Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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();
        }
    });
1
On

You can not create MusicService in Android like simple class. It is a service and it must be started in a right way https://medium.com/google-developers/mediabrowserservicecompat-and-the-modern-media-playback-app-7959a5196d90