Java – Saves data in Fragments when the Android screen rotates

Saves data in Fragments when the Android screen rotates… here is a solution to the problem.

Saves data in Fragments when the Android screen rotates

Who can help me solve my problem?

I have one activity and six fragments.

A fragment contains a link to my MediaPlayer class, which I use to display some videos in the fragment.
I got a link to each Fragment class in the onCreate() method of the activity.
Every time the screen rotates, the onCreate() method is called, and I get new links to my six Fragment classes (and the new MediaPlayer).

Can I save every link to my Fragment class before rotation and then get it back?
(e.g. I save the link to my fragment with the link of the media player class, then call my MediaPlayer’s stop() method, then when the screen rotates, I recover all the data, my MediaPlayer and call the ResumePlay() method).

Or is it

a bad idea that I need to recreate the link every time and the only thing I need to do is save the current video time and file path in onSaveInstanceState and then retrieve it in onRestoreInstanceState, starting a new MediaPlyer recovery over time?

Thanks!

Solution

For each class that extends the fragment in your application, store the value to persist when you change the screen orientation in the onSaveInstanceState method, and then persist in the onCreateView method.

For example, for the video issue you are experiencing, you can do this:

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("cp", videoview.getCurrentPosition());  
 }

Then keep it like this

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    if(savedInstanceState!=null)
    {
        int a=savedInstanceState.getInt("cp");
        videoview.seekTo(a);
    }

the rest of your code then....
}

Hope I can find you.

Related Problems and Solutions