Losing 'MediaPlayer' (& other Variables) when Device is Rotated

后端 未结 4 1481
独厮守ぢ
独厮守ぢ 2021-01-07 13:06

I\'m creating a music player for Android and it\'s mostly working. The problem is that when I turn the device horizontally I lose all the variables from the Activity (which

4条回答
  •  北海茫月
    2021-01-07 13:38

    For objects you couldn't pass via a bundle, I would suggest you to use the simple SharedPreference to store objects. Here you have a simple implementation:

    public class Data {
         private SharedPreferences preferences; 
         private int test; 
    
         public Data (Context context)
         {          
            preferences = context.getSharedPreferences("Data", 0);
            test = preferences.getInt("test", 0);
         }
    
         public int getTest()
         {       
                 return test;
         }
    
         public void setTest(int input)
         {       
            this.test = input;
            SharedPreferences.Editor editor = preferences.edit();
            editor.putInt("Test", input);
            editor.commit();
         }    
    }
    

    You have just to initialize the variable in the onCreate():

    Data mydata = new Data(this);

    And you can use set/get with mydata to store/retrieve your persistent data.

    Edit: It is maybe not suitable for MediaPlayer objects, but for other classical types (int, string, boolean...).

提交回复
热议问题