Search code examples
androidaudiosharedpreferencesplaybackmute

Android: How to get app to remember if mute button has been pressed or not


I have successfully created a button that mute my button press sound if wanted. The problem I am having is that when I leave the page or close the app and return sound a returned to the default of being on. I am trying to achieve this through preferences but it is not working. I have used preferences before to successfully store high scores but I can get it to work this time as I intend. Here is my sound code:

import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;

public class homePage extends Activity {
    ;
    Button Mute;

        int Sound = 1;


     public void onCreate(Bundle savedInstanceState) { 
         setContentView(R.layout.home_page);

         Mute = (Button) findViewById(R.id.mute);
          setButtonOnClickListeners();

             RelativeLayout layout = new RelativeLayout(this);

             layout = (RelativeLayout) findViewById(R.id.home);



     }
     public void onPause(Bundle savedInstanceState) { 
         SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("SP", Context.MODE_PRIVATE);
         Editor editor = sharedPrefs.edit();
         editor.putInt("SP", Sound);
         editor.commit();


     }
     public void onResume(Bundle savedInstanceState) {   SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("SP", Context.MODE_PRIVATE);
     int counter = sharedPrefs.getInt("SP", 0);}

     public void sound(){
         final MediaPlayer mp = new MediaPlayer();
         if (Sound==1){
         try {

                AssetFileDescriptor afd;
                afd = getAssets().openFd("butpress.mp3");
                mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
             mp.prepare();
                mp.start();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
     }else if(Sound==0){mp.stop();}}


     private void setButtonOnClickListeners(){

         Mute.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v) {
                    if(Sound==1){
                        Mute.setBackgroundResource( R.drawable.sound_off);
                        --Sound;

                    }
                    else if(Sound==0){
                        Mute.setBackgroundResource( R.drawable.sound_high);
                        Sound++;
                    }

                }


            });


}
}

The muting of sound works I just need it to save, and idea whats going wrong?

UPDATE 1:

Here is the edited code.

public class homePage extends Activity {

    Button Mute;

        int Sound = 0;
        private final static String PREFS_KEY = "shared_prefs"; 
     public void onCreate(Bundle savedInstanceState) { 
         setContentView(R.layout.home_page);

          super.onCreate(savedInstanceState); 

         Mute = (Button) findViewById(R.id.mute);
          setButtonOnClickListeners();


             onResume();// is this needed here? not noticed any difference either way   

             if(Sound==1){
                    Mute.setBackgroundResource( R.drawable.sound_high);
                    getSharedPreferences("PREFS_KEY", Context.MODE_PRIVATE).edit().putBoolean("mute_pressed", true).commit();

                }
                else if(Sound==0){
                    Mute.setBackgroundResource( R.drawable.sound_off);
                    getSharedPreferences("PREFS_KEY", Context.MODE_PRIVATE).edit().putBoolean("mute_pressed", true).commit();

                }

            }



     public void sound(){
         final MediaPlayer mp = new MediaPlayer();
         if (Sound==1){
         try {

                AssetFileDescriptor afd;
                afd = getAssets().openFd("butpress.mp3");
                mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
             mp.prepare();
                mp.start();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
     }else if(Sound==0){mp.stop();}}


     private void setButtonOnClickListeners(){


         Mute.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v) {
                    if(Sound==1){
                        Mute.setBackgroundResource( R.drawable.sound_off);
                        --Sound;
                        getSharedPreferences("PREFS_KEY", Context.MODE_PRIVATE).edit().putBoolean("mute_pressed", true).commit();

                    }
                    else if(Sound==0){
                        Mute.setBackgroundResource( R.drawable.sound_high);
                        Sound++;
                        getSharedPreferences("PREFS_KEY", Context.MODE_PRIVATE).edit().putBoolean("mute_pressed", true).commit();

                    }

                }


            });


} public void onPause(Bundle savedInstanceState) { 
     SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("PREFS_KEY", Context.MODE_PRIVATE);
     Editor editor = sharedPrefs.edit();
     editor.putInt("SP", Sound);
     editor.commit();


}
public void onResume(Bundle savedInstanceState) {    SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("PREFS_KEY", Context.MODE_PRIVATE);
Sound = sharedPrefs.getInt("SP", 0);}

}

I don't think the correct number is being stored


Solution

  • In your OnClickListener's onClick method you can save the state

    getSharedPreferences("SP", Context.MODE_PRIVATE).edit().putBoolean("mute_pressed", true).commit();
    

    or if you want to save the int value like you are in onPause just do

    getSharedPreferences("SP", Context.MODE_PRIVATE).edit().putBoolean("mute_val", Sound).commit();
    

    Because as of right now you aren't actually saving as you increment/decrement you are only saving onPause(). You can then restore that value in onResume() by changing

    int counter = ...
    // to
    Sound =...
    

    This will set your classes Sound variable to the old stored value.

    I would also recommend, instead of using "SP" (I highly recommend against using the same key values for your shared preference key and your stored value key while I am at it), to use static variables you set in the top of your class as something like

    private final static String PREFS_KEY = "shared_prefs";
    

    then use your variables like

    getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)...
    

    this helps with localization. You should also check into naming conventions in Java to avoid headaches down the road when things get more complicating.

    UPDATED TO WORK WITH YOUR CODE

    // this should be HomePage, not homePage
    public class homePage extends Activity {
    
        private final static String PREFS_KEY = "shared_prefs";
        private final static String MUTE_PRESSED_KEY = "mute_pressed";
    
        private Button Mute;    // this should be mute, not Mute
        private int Sound = 0;  // this should be sound, not Sound
        private SharedPreferences prefs;
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.home_page);
    
            Mute = (Button) findViewById(R.id.mute);
            setButtonOnClickListeners();
    
            prefs = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
            if(prefs.getBoolean(MUTE_PRESSED_KEY, false))
                Sound = 1;
            else
                Sound = 0;
        }
    
        // I DIDN'T REALLY LOOK AT THIS SO COUNTING ON YOU THAT IT WORKS
        public void sound() {
            final MediaPlayer mp = new MediaPlayer();
            if (Sound == 1) {
                try {
                    AssetFileDescriptor afd;
                    afd = getAssets().openFd("butpress.mp3");
                    mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
                            afd.getLength());
                    mp.prepare();
                    mp.start();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (Sound == 0) {
                mp.stop();
            }
        }
    
        private void setButtonOnClickListeners() {
    
            Mute.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Sound == 1) {
                        Mute.setBackgroundResource(R.drawable.sound_off);
                        Sound = 0;
                        prefs.edit().putBoolean(MUTE_PRESSED_KEY, false).commit();
    
                    } else if (Sound == 0) {
                        Mute.setBackgroundResource(R.drawable.sound_high);
                        Sound = 1;
                        prefs.edit().putBoolean(MUTE_PRESSED_KEY, true).commit();
                    }
    
                }
    
            });
    
        }
    
    }