2

I would like to automatically play music in the background when I enter this Fragment page. I believe the commented out section is how you implement it, but I might be typing the first parameter incorrectly?

public class AlphabetFragment extends Fragment {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    //MediaPlayer mysong;
    //mysong = MediaPlayer.create(AlphabetFragment.this, R.raw.alphabetlist);
    //mysong.start();

    return inflater.inflate(R.layout.fragment_alphabet, container, false);
}

Or am I coding this in the wrong spot, should it be part of the MainActivity.java?

case R.id.nav_alphabet:

getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new AlphabetFragment()).commit();
                    //mysong = MediaPlayer.create(AlphabetFragment., R.raw.alphabetlistm4a);
                    //mysong.start();
Nordle
  • 2,915
  • 3
  • 16
  • 34
J. Wu
  • 23
  • 2

2 Answers2

0

Use getActivity(). It gives the Media Player the context it needs. Try to use this code:

MediaPlayer mp = MediaPlayer.create( getActivity() , R.raw.alphabetlist );

Your fragment code should look like this:

MediaPlayer mp; 
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

    mp=MediaPlayer.create(getActivity(), R.raw.alphabetlist); 
    mp.start():  

    return inflater.inflate(R.layout.fragment_alphabet, container, false);
}

Try this. Hope it helps!

itsmysterybox
  • 2,748
  • 3
  • 21
  • 26
  • Thanks, first time using the site. By any chance you have a suggestion for my next problem. So I would like the music to play in the background when I click into a fragment layout. However, when I exit it the layout... I would like the music to stop and play whatever the new fragment page is playing. Is it possible, and how? I believe I can save myself a lot of headache by just creating a button, but I really do not want to do that. – J. Wu Oct 15 '18 at 08:48
  • Are you trying something like [this](https://stackoverflow.com/questions/32145170/how-to-i-achieve-viewpager-next-previous-in-music-player-app)? And with "play in the background", do you mean that playing music should show in notification? – itsmysterybox Oct 16 '18 at 07:46
0

You could just use getActivity to get the context of activity from fragment class.

As below.

public class AlphabetFragment extends Fragment {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    MediaPlayer mysong;
    mysong = MediaPlayer.create(this.getActivity(), R.raw.alphabetlist);
    mysong.start();

    return inflater.inflate(R.layout.fragment_alphabet, container, false);
}
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44