Cannot make a static reference to the non-static method getAssets() - Trouble playing Audio in a fragment

android, audio, fragment, static

Solution

You need to use a Context object, so in this example you could use:

`rootView.getContext().getAssets().openFd("a.mp3");`

That said, I would suggest moving this code later in the Fragment Lifecycle in `onActivityCreated` or `onStart` after the view hierarchy has been instantiated. Putting this code in `onCreateView` could delay/slow down showing the UI to the user.

From those later lifecycle methods, you can safely call: `getResources().getAssets().openFd("a.mp3");`

Problem

So, I'm making an app with Scrollable Tabs + Swipe navigation. In every tab's page I want to play a different audio file. Below is my fragment's OnCreateView, containing initialization of the mediaplayer, FileDescriptor and playing an audio file named a.mp3 in the assets folder. ``` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false); ///Playing sound from here on AssetFileDescriptor fda; MediaPlayer amp = new MediaPlayer(); try { fda = getAssets().openFd("a.mp3");//// GIVES ERROR ! amp.reset(); amp.setDataSource(fda.getFileDescriptor()); amp.prepare(); amp.start(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return rootView; } } ``` The GetAssets() method gives an error as following : ``` Cannot make a static reference to the non-static method getAssets() from the type ContextWrapper ``` Although this same piece of code from declaring the FileDescriptor to the final Catch Statement works perfectly in a normal blank activity's OnCreate. It's not working here. Any solutions for this ? Can I make the getAssets() method static somehow ? Any other way to access the audio file from the Fragment ? (Remember, my goal is to play a different audio file in each of the different tab's screens. I'll add more audio files later, Just trying to get at least this one to work first.) Pls Help :) Thank you !

Original source