Android Studio- save object in sharedPreferences [duplicated]

1

I want to save an object in sharedPreferences but I do not know how it is done. Could someone guide me with an example?

    
asked by Fernando Godoy 10.03.2017 в 05:58
source

1 answer

1

SharedPreferences work the same as a hash table, storing by key / value. These are saved in an XML file in the application folder inside the mobile device.

The Andorid API that you should use is the SharedPreferences .

Form of work:

  • The same name must always be used to access them
  • There are two forms of access
    • getSharedPreferences (mode) and getSharedPreferences (name, mode)
  • There are three access modes:
    • Private (Context.MODE_PRIVATE): Only the application or applications with the same User ID can access these
    • Read (Context.MODE_WORLD_READABLE): Other applications can read them. Very dangerous
    • Writable (Context.MODE_WORLD_WRITEABLE): Other applications can edit them. Very dangerous
  • For security, the best thing is that the preferences are private. The other accesses are not recommended by Android.

How to save in them:

  • With the SharedPreferences.Editor object we introduce the preferences
  • Once entered, you have to save them using the commit () method
  • You can save Set objects from API 11

    SharedPreferences preferences = getSharedpreferences("Ejemplo", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean("registrado", true);
    

How to load them:

  • To load the preferences we have to use the same name that we use when saving them
  • The second parameter indicates the default value that the field takes if the preference does not exist

    SharedPreferences preferences = getSharedpreferences("Ejemplo", Context.MODE_PRIVATE);
    boolean registrado = preferences.getBoolean("registrado", true);
    
answered by 10.03.2017 / 08:52
source