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.