Preferences settings save open read write application Android example

Android app setup preferences, settings, open, read, write, onStop(), onPause(), getSharedPreferences(), SharedPreferences.Editor getInt(), getBoolean(), getString() , putInt(), putString(), putBoolean() example source code.

 
import android.content.SharedPreferences;
 
public class MainClass extends Activity {
  public static final String PREFERENCES_NAME = "MyPrefsFile";
  String myNewString;
  int myNewInt;
  Boolean myNewBool;
 
 
   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // read old settings if exist
      SharedPreferences settings = getSharedPreferences(PREFERENCES_NAME, 0);
 
     String sDefault = "Hello!";
      String sStringFromPrefFile = settings.getString("myString", sDefault); // new text  or default Hello!
 
      int nDefaultIndex = 2; //
      int nIndexFromPrefFile = settings.getInt("myInt", nDefaultIndex); // 4 or default 2
 
      Boolean bDefault = false;
      Boolean bFromPrefFile = settings.getBoolean("silentMode", bDefault); // true or default false
 
 
        // new settings will saved in onStop or onPause
        myNewString = "new text";
        myNewInt = 4;
        myNewBool = true;
     }   
 
    @Override
    protected void onPause() {
    	super.onPause();
        Toast.makeText(getApplicationContext(), "onPause "
        		, Toast.LENGTH_SHORT).show();
 
    	savePreferences();
    }
 
    @Override
    protected void onStop() {
    	super.onStop();
    	savePreferences();
    }
    /**save settings*/	
    public void savePreferences(){
    	try {
    		SharedPreferences settings = getSharedPreferences(PREFERENCES_NAME, 0);
    		SharedPreferences.Editor editor = settings.edit();
 
    		editor.putString("myString", myNewString);
     		editor.putInt("nMyInt", myNewInt);
    		editor.putBoolean("silentMode", myNewBool); // 
 
    		editor.commit();
    	} catch (Exception e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
 
    }	
}
This entry was posted in Android Examples Code and tagged , , , , , , , , . Bookmark the permalink.


Comments are closed.



7,063 views