我有一个想要与服务器通信的碎片,但问题是我总是得到空指针
我的片段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
}
});
}
}
这是我的服务:
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");
//}
}
}
我得到了这个致命的例外:主要
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
我希望你能帮助我
答案 0 :(得分:0)
您无法在Android中像简单类一样创建MusicService。这是一项服务,必须以正确的方式https://medium.com/google-developers/mediabrowserservicecompat-and-the-modern-media-playback-app-7959a5196d90
启动答案 1 :(得分:0)
在MusicService中,我添加了此方法
public void pausePlay() {
PauseRequest();
}
然后在BrowseFragment中,onCreateView()
Button button = (Button)rootView.findViewById(R.id.button_play_pause);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mMusicService.pausePlay();
}
});