简体   繁体   中英

Fragment in Android for MediaPlayer getting null pointers?

I have this code:

    Button one = (Button)getView().findViewById(R.id.button_audio);
    final MediaPlayer mp = MediaPlayer.create(getActivity().getApplicationContext(), R.raw.idontlike);
    one.setOnClickListener(new OnClickListener(){

        public void onClick(View v) {
            mp.start();
        }
    });

I'm getting this error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference

You need to search in the fragment layout so try the following

View myView= inflater.inflate(R.layout.fragment_main, container, false);
Button one = (Button) myView.findViewById(R.id.button);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM