This is my blog where I hope to post information about what I am doing technically and what my family is up to. I hope you enjoy

Friday, May 14, 2010

Android Shared Preferences

Android has a concept of an application storing default information in a preference. Example would be when a user first down loads an Android application installs and configures the application with some setting like email or user name. During the setting of the application the information retrieved from the user can be stored in the SharedPreference API. This is a very easy way to save data that can be used later even after the application is stopped and restarted.

public class ConfigActivity extends Activity {
     public void onCreate( Bundle state ) {
         super.onCreate( state );
         // Show the config settings in View
         saveButton = findByViewId(...);
         saveButton.setOnClickListener( new View.OnClickListener() {
                   public void onClick(View v ) {
                      saveEmail(user, pass);
                   }
          });
         // Get Email and place into config Text box
      }
protected void saveEmail( String user, String pass ) {  
         SharedPreferences pref = null;
         getSharedPreferences( "EMAIL_SETTINGS", this.MODE_WORLD_WRITEABLE );
// Must edit and commit
         Editor edit = pref.edit();
         edit.putString("emailName", user);
         edit.putString("emailPassword", pass);
         edit.commit();
      }
protected String getEmail() {
         SharedPreferences pref =
         getSharedPreferences("EMAIL_SETTINGS", this.MODE_WORLD_READABLE );
         String email = pref.getString( "emailName" , null); 
         return email;
      }
}

No comments:

Post a Comment

Layout-->Edit HTML -->