I am trying make a radio streaming app in android studio using setAudioAttributes, but i when install the application in my phone shows the next error:
error java.lang.nullpointerexception: attempt to invoke virtual method void android.media.mediaplayer.setaudioattributes(android.media.AudioAttributes) on a null object reference
Thanks.
public class Radio extends Fragment {
Button play_pause;
MediaPlayer mp;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.radio, container, false);
play_pause = (Button) view.findViewById(R.id.btnplay);
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
mp.setAudioAttributes(new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build());
mp.setDataSource("http://198.27.83.65:9962/;stream.mp3");
mp.prepare();
mp.start();
}
else {
Toast.makeText(getContext(),"Error",Toast.LENGTH_SHORT).show();
}
}
catch (Exception e){
Toast.makeText(getContext(),"Error" + e,Toast.LENGTH_SHORT).show();
}
//mp = MediaPlayer.create(this.getContext(), R.raw.radio);
play_pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mp.isPlaying()) {
mp.pause();
Toast.makeText(getContext(),"Stop",Toast.LENGTH_SHORT).show();
}
else {
mp.start();
Toast.makeText(getContext(),"Start",Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}