This is the code I use to save the string representation of the Uri to the SharedPreferences:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE_PICK_SOUNDFILE && resultCode == Activity.RESULT_OK){
if ((data != null) && (data.getData() != null)){
SharedPreferences sharedPref = getSharedPreferences("customName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("uritostring", data.getData().toString());
editor.apply();
}
}
}
Note that when I append either of the following two right here it works without a problem:
MediaPlayer mp=MediaPlayer.create(this,data.getData());
MediaPlayer mp=MediaPlayer.create(this,Uri.parse(data.getData().toString()));
However when I try to create a MediaPlayer later in another activity like this, it does not work:
SharedPreferences sharedPref = getSharedPreferences("customName", Context.MODE_PRIVATE);
Uri uri = Uri.parse(sharedPref.getString("uritostring","defaultUriString"));
mp.create(this,uri);
I'm lost at what difference the saving and loading to sharedPreferences could reasonably make. From debugging as far as I can tell uri is identical to the result of Uri.parse(data.getData().toString()) from above.
Any help and pointers are greatly appreciated.
Best regards
Julius
EDIT:
I thought I solved this by calling the MediaPlayer.create()
method with the getApplicationContext()
context, but closing the application and reopening it renders the method call disfunctional again.