I did not test the code, but your logic was wrong. You were not saving the preference on click.
Boolean sound;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ib1= (ImageButton) findViewById(R.id.imageButton1);
getpref();
ib1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(sound==true){
sound = false;
ib1.setImageResource(R.drawable.volume);
} else{
sound = true;
ib1.setImageResource(R.drawable.vol);
}
setSoundChecked(sound);
}
});
};
void setSoundChecked(Boolean checked) {
SharedPreferences pref = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putBoolean("key", checked);
editor.commit();
}
public void getpref() {
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
Boolean sh_sound = prefs.getBoolean("key", true);
sound = sh_sound;
checkpref(sh_sound);
}
public void checkpref(Boolean sh_sound) {
if(sh_sound== true){
ib1.setImageResource(R.drawable.vol);
}
else{
ib1.setImageResource(R.drawable.volume);
}
}