-1

I have been writing a media player app, every thing is working fine when my media player code is placed in MainActivity.java. To try and make the code a bit more tidy. I have moved the code to a fragment, (MediaPlayerFragment) and have been able to get the code to work by including in the fragment a defining string variable pointing to a (Uri) mp3 file. However what I need to do is pass a string variable from MainActivity.java to MediaPlayerFragment.java. I have been look every where for a solution for this simple task. I need to pass it to the java not the xml.Can any one help?

Code that have tried is:

******* MainActivity.java ------------------------------

public String filepath = "/storage/emulated/0/Download/music.mp3";


  //  ************ Send File name String to Fragment ****************

 MediaPlayerFragment fragment = MediaPlayerFragment.newInstance(this, filepath);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_media_player, fragment).commit();


MediaPlayerFragment.java -------------------------------

public String filepath;


 //  *************** Get File name String from Main ***************

 public static com.dave.audioplayer.MediaPlayerFragment newInstance(MainActivity text, String filepath){

com.dave.audioplayer.MediaPlayerFragment fragment = new com.dave.audioplayer.MediaPlayerFragment();
        Bundle args = new Bundle();

     args.putString(ARG_TEXT, filepath);
       
        fragment.setArguments(args);
        
          return fragment;
         }


//********** Initialize media player **********

final MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(), Uri.parse(filepath));

Can also help test code with:

Toast.makeText(this, "Path: " + filepath, Toast.LENGTH_LONG).show();

However the fragment side does not like this statement, probably due to the problem and I guess it will work if the problem is solved.

John Conde
  • 217,595
  • 99
  • 455
  • 496

1 Answers1

0

You will need to use the getArguments() fragment method which gives you the argument bundle set in the newInstance() method, then use getCharSequence(ARG_TEXT).toString()

So the code in your Media Fragment would be:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ...
        Bundle b = getArguments();
        filepath = b.getCharSequence(ARG_TEXT).toString();
        ...
}
Yirmi
  • 332
  • 2
  • 13
  • Thanks Still not working though. it is returning a null, and says filepath redundant, have tried adding if (getArguments() != null) but makes no difference. – Dave Rockwizard May 12 '21 at 15:25
  • Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.os.Bundle.getCharSequence(java.lang.String)' on a null object reference – Dave Rockwizard May 13 '21 at 07:45
  • Caused by: java.lang.NullPointerException: uriString – Dave Rockwizard May 13 '21 at 07:46