bukka.wh bukka.wh - 4 years ago 249
Java Question

Save data in Fragments on screen rotation in Android

Can anyone help me to solve my problem?

I have an activity and six fragments.

One fragment contains a link to my MediaPlayer class, which I use to show some video in a fragment.

I get a link for every Fragment class in onCreate() method of my Activity.

Each time the screen rotates, the onCreate() method is called and I get new links to my six Fragment classes (and new MediaPlayer).

Can I save every link to my Fragment classes before rotation and then get it back?

(For example: I am saving links to my fragments with the link to media player class, then call stop() method of my MediaPlayer, then when the screen rotated, I restore all data, and my MediaPlayer and call ResumePlay() method).

Or is this a bad idea and I need recreate links every time, and the only thing I need to do is to save the current time of video and path to file in onSaveInstanceState, then get it back in onRestoreInstanceState, start new MediaPlyer with time that was restored?

Thank you!

Answer Source

for each class extending fragment inside your application store the value you want to retain it when you change the screen orientation inside onSaveInstanceState method and then retain inside onCreateView method.

for example for the video problem you are having , you can do something like this:

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

then retain it like this

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        int a=savedInstanceState.getInt("cp");

//the rest of your code then....

hope i got you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download