Cómo utilizar SharedPreferences en Android para almacenar, buscar y editar valores

Quiero almacenar un valor de tiempo y necesito recuperarlo y editarlo. ¿Cómo puedo utilizar SharedPreferences para hacer esto?

Para obtener preferencias compartidas, utilice el siguiente método En su actividad:

 SharedPreferences prefs = this.getSharedPreferences( "com.example.app", Context.MODE_PRIVATE); 

Para leer las preferencias:

 String dateTimeKey = "com.example.app.datetime"; // use a default value using new Date() long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

Para editar y guardar preferencias

 Date dt = getSomeDate(); prefs.edit().putLong(dateTimeKey, dt.getTime()).apply(); 

El directorio de ejemplo de android sdk contiene un ejemplo de recuperación y almacenamiento de preferencias compartidas. Su situado en el:

 <android-sdk-home>/samples/android-<platformversion>/ApiDemos directory 

Editar ==>

Me di cuenta, es importante escribir la diferencia entre commit() y apply() aquí también.

commit() devuelve true si el valor se guarda con éxito o false . Guarda los valores en SharedPreferences de forma sincrónica .

apply() se agregó en 2.3 y no devuelve ningún valor en caso de éxito o falla. Guarda valores en SharedPreferences inmediatamente pero inicia un commit asincrónico . Más detalle está aquí .

Para almacenar valores en preferencias compartidas:

 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = preferences.edit(); editor.putString("Name","Harneet"); editor.apply(); 

Para recuperar valores de las preferencias compartidas:

 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String name = preferences.getString("Name", ""); if(!name.equalsIgnoreCase("")) { name = name + " Sethi"; /* Edit the value here*/ } 

Para editar datos de la preferencia compartida

  SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); editor.putString("text", mSaved.getText().toString()); editor.putInt("selection-start", mSaved.getSelectionStart()); editor.putInt("selection-end", mSaved.getSelectionEnd()); editor.apply(); 

Para recuperar datos de preferencias compartidas

 SharedPreferences prefs = getPreferences(MODE_PRIVATE); String restoredText = prefs.getString("text", null); if (restoredText != null) { //mSaved.setText(restoredText, TextView.BufferType.EDITABLE); int selectionStart = prefs.getInt("selection-start", -1); int selectionEnd = prefs.getInt("selection-end", -1); /*if (selectionStart != -1 && selectionEnd != -1) { mSaved.setSelection(selectionStart, selectionEnd); }*/ } 

Editar-

Tomé este fragmento del ejemplo de demostración de API. Tenía un cuadro de edición de texto allí … En este contexto no es obligatorio. Estoy comentando lo mismo

Escribir :

 SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_WORLD_WRITEABLE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("Authentication_Id",userid.getText().toString()); editor.putString("Authentication_Password",password.getText().toString()); editor.putString("Authentication_Status","true"); editor.apply(); 

Leer :

 SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE); String Astatus = prfs.getString("Authentication_Status", ""); 

La manera más fácil:

Ahorrar:

 getPreferences(MODE_PRIVATE).edit().putString("Name of variable",value).commit(); 

Para recuperar:

 your_variable = getPreferences(MODE_PRIVATE).getString("Name of variable",default value); 

Valores de ajuste en Preferencia:

 // MY_PREFS_NAME - a static String variable like: //public static final String MY_PREFS_NAME = "MyPrefsFile"; SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit(); editor.putString("name", "Elena"); editor.putInt("idName", 12); editor.commit(); 

Recuperar datos de preferencia:

 SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); String restoredText = prefs.getString("text", null); if (restoredText != null) { String name = prefs.getString("name", "No name defined");//"No name defined" is the default value. int idName = prefs.getInt("idName", 0); //0 is the default value. } 

más información:

Uso de preferencias compartidas

Preferencias compartidas

Para almacenar información

  SharedPreferences preferences = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("username", username.getText().toString()); editor.putString("password", password.getText().toString()); editor.putString("logged", "logged"); editor.commit(); 

Para restablecer sus preferencias

  SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.commit(); 

Si está realizando una aplicación grande con otros desarrolladores de su equipo y tiene la intención de tener todo bien organizado sin código disperso o diferentes instancias de SharedPreferences, puede hacer algo como esto:

 //SharedPreferences manager class public class SharedPrefs { //SharedPreferences file name private static String SHARED_PREFS_FILE_NAME = "my_app_shared_prefs"; //here you can centralize all your shared prefs keys public static String KEY_MY_SHARED_BOOLEAN = "my_shared_boolean"; public static String KEY_MY_SHARED_FOO = "my_shared_foo"; //get the SharedPreferences object instance //create SharedPreferences file if not present private static SharedPreferences getPrefs(Context context) { return context.getSharedPreferences(SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE); } //Save Booleans public static void savePref(Context context, String key, boolean value) { getPrefs(context).edit().putBoolean(key, value).commit(); } //Get Booleans public static boolean getBoolean(Context context, String key) { return getPrefs(context).getBoolean(key, false); } //Get Booleans if not found return a predefined default value public static boolean getBoolean(Context context, String key, boolean defaultValue) { return getPrefs(context).getBoolean(key, defaultValue); } //Strings public static void save(Context context, String key, String value) { getPrefs(context).edit().putString(key, value).commit(); } public static String getString(Context context, String key) { return getPrefs(context).getString(key, ""); } public static String getString(Context context, String key, String defaultValue) { return getPrefs(context).getString(key, defaultValue); } //Integers public static void save(Context context, String key, int value) { getPrefs(context).edit().putInt(key, value).commit(); } public static int getInt(Context context, String key) { return getPrefs(context).getInt(key, 0); } public static int getInt(Context context, String key, int defaultValue) { return getPrefs(context).getInt(key, defaultValue); } //Floats public static void save(Context context, String key, float value) { getPrefs(context).edit().putFloat(key, value).commit(); } public static float getFloat(Context context, String key) { return getPrefs(context).getFloat(key, 0); } public static float getFloat(Context context, String key, float defaultValue) { return getPrefs(context).getFloat(key, defaultValue); } //Longs public static void save(Context context, String key, long value) { getPrefs(context).edit().putLong(key, value).commit(); } public static long getLong(Context context, String key) { return getPrefs(context).getLong(key, 0); } public static long getLong(Context context, String key, long defaultValue) { return getPrefs(context).getLong(key, defaultValue); } //StringSets public static void save(Context context, String key, Set<String> value) { getPrefs(context).edit().putStringSet(key, value).commit(); } public static Set<String> getStringSet(Context context, String key) { return getPrefs(context).getStringSet(key, null); } public static Set<String> getStringSet(Context context, String key, Set<String> defaultValue) { return getPrefs(context).getStringSet(key, defaultValue); } } 

En tu actividad puedes guardar SharedPreferences de esta manera

 //saving a boolean into prefs SharedPrefs.savePref(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN, booleanVar); 

Y puede recuperar sus SharedPreferences de esta manera

 //getting a boolean from prefs booleanVar = SharedPrefs.getBoolean(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN); 

En cualquier aplicación, hay preferencias predeterminadas a las que se puede acceder a través de la instancia de PreferenceManager y su método relacionado getDefaultSharedPreferences (Context)

Con la instancia SharedPreference se puede recuperar el valor int de cualquier preferencia con getInt (String key, int defVal) . La preferencia que nos interesa en este caso es counter

En nuestro caso, podemos modificar la instancia de SharedPreference en nuestro caso usando el método de edición () y usar el putInt (String key, int newVal) Aumentamos el recuento para nuestra aplicación que presist más allá de la aplicación y se muestra en consecuencia.

Para continuar la demostración de esto, reiniciar y su aplicación de nuevo, notará que el recuento aumentará cada vez que reinicie la aplicación.

PreferencesDemo.java

Código:

 package org.example.preferences; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.widget.TextView; public class PreferencesDemo extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Get the app's shared preferences SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this); // Get the value for the run counter int counter = app_preferences.getInt("counter", 0); // Update the TextView TextView text = (TextView) findViewById(R.id.text); text.setText("This app has been started " + counter + " times."); // Increment the counter SharedPreferences.Editor editor = app_preferences.edit(); editor.putInt("counter", ++counter); editor.commit(); // Very important } } 

Main.xml

Código:

  <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout> 

Clase Singleton Preferencias Compartidas. Puede ayudar a otros en el futuro.

  import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; public class SharedPref { private static SharedPreferences mSharedPref; public static final String NAME = "NAME"; public static final String AGE = "AGE"; public static final String IS_SELECT = "IS_SELECT"; private SharedPref() { } public static void init(Context context) { if(mSharedPref == null) mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE); } public static String read(String key, String defValue) { return mSharedPref.getString(key, defValue); } public static void write(String key, String value) { SharedPreferences.Editor prefsEditor = mSharedPref.edit(); prefsEditor.putString(key, value); prefsEditor.commit(); } public static boolean read(String key, boolean defValue) { return mSharedPref.getBoolean(key, defValue); } public static void write(String key, boolean value) { SharedPreferences.Editor prefsEditor = mSharedPref.edit(); prefsEditor.putBoolean(key, value); prefsEditor.commit(); } public static Integer read(String key, int defValue) { return mSharedPref.getInt(key, defValue); } public static void write(String key, Integer value) { SharedPreferences.Editor prefsEditor = mSharedPref.edit(); prefsEditor.putInt(key, value).commit(); } } 

Simplemente llame a SharedPref.init () en MainActivity una vez

 SharedPref.init(getApplicationContext()); 

Para escribir datos

 SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference. SharedPref.write(SharedPref.AGE, "25");//save int in shared preference. SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference. 

Para leer datos

 String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference. String age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference. String isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference. 

Solución simple de cómo almacenar el valor de inicio de sesión en SharedPreferences .

Puede extender la clase MainActivity u otra clase donde almacenará el "valor de algo que desea conservar". Ponga esto en las clases del escritor y del lector:

 public static final String GAME_PREFERENCES_LOGIN = "Login"; 

Aquí InputClass es entrada y OutputClass es clase de salida, respectivamente.

 // This is a storage, put this in a class which you can extend or in both classes: //(input and output) public static final String GAME_PREFERENCES_LOGIN = "Login"; // String from the text input (can be from anywhere) String login = inputLogin.getText().toString(); // then to add a value in InputCalss "SAVE", SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0); Editor editor = example.edit(); editor.putString("value", login); editor.commit(); 

Ahora puedes usarlo en otro lugar, como en otras clases. Lo siguiente es OutputClass .

 SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0); String userString = example.getString("value", "defValue"); // the following will print it out in console Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString); 

La idea básica de SharedPreferences es almacenar cosas en un archivo XML.

  1. Declare la ruta de su archivo xml (si no tiene este archivo, Android lo creará. Si tiene este archivo, Android lo accederá.)

     SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); 
  2. Escribir valor en las preferencias compartidas

     prefs.edit().putLong("preference_file_key", 1010101).apply(); 

    La preference_file_key es el nombre de los archivos de preferencias compartidas. Y el 1010101 es el valor que necesita almacenar.

    apply() al fin es guardar los cambios. Si obtiene el error de apply() , cámbielo por commit() . Así que esta oración alternativa es

     prefs.edit().putLong("preference_file_key", 1010101).commit(); 
  3. Leer desde Preferencias compartidas

     SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); long lsp = sp.getLong("preference_file_key", -1); 

    lsp será -1 si preference_file_key no tiene valor. Si 'preference_file_key' tiene un valor, devolverá el valor de esto.

El código completo para la escritura es

  SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); // Declare xml file prefs.edit().putLong("preference_file_key", 1010101).apply(); // Write the value to key. 

El código de lectura es

  SharedPreferences sf = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); // Declare xml file long lsp = sp.getLong("preference_file_key", -1); // Read the key and store in lsp 

Almacenar en SharedPreferences

 SharedPreferences preferences = getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE); Editor editor = preferences.edit(); editor.putString("name", name); editor.commit(); 

Buscar en SharedPreferences

 SharedPreferences preferences=getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE); String name=preferences.getString("name",null); 

Nota: "temp" es el nombre de preferencias compartidas y "nombre" es el valor de entrada. Si el valor no sale entonces devuelve nulo

Puede guardar valor con este método:

 public void savePreferencesForReasonCode(Context context, String key, String value) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(key, value); editor.commit(); } 

Y con este método puede obtener valor de SharedPreferences:

 public String getPreferences(Context context, String prefKey) { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); return sharedPreferences.getString(prefKey, ""); } 

Aquí prefKey es la clave que utilizó para guardar el valor específico. Gracias.

Mejor práctica siempre

Crear interfaz denominada con PreferenceManager :

 // Interface to save values in shared preferences and also for retrieve values from shared preferences public interface PreferenceManager { SharedPreferences getPreferences(); Editor editPreferences(); void setString(String key, String value); String getString(String key); void setBoolean(String key, boolean value); boolean getBoolean(String key); void setInteger(String key, int value); int getInteger(String key); void setFloat(String key, float value); float getFloat(String key); } 

Cómo utilizar con Actividad / Fragmento :

 public class HomeActivity extends AppCompatActivity implements PreferenceManager{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout_activity_home); } @Override public SharedPreferences getPreferences(){ return getSharedPreferences("SP_TITLE", Context.MODE_PRIVATE); } @Override public SharedPreferences.Editor editPreferences(){ return getPreferences().edit(); } @Override public void setString(String key, String value) { editPreferences().putString(key, value).commit(); } @Override public String getString(String key) { return getPreferences().getString(key, ""); } @Override public void setBoolean(String key, boolean value) { editPreferences().putBoolean(key, value).commit(); } @Override public boolean getBoolean(String key) { return getPreferences().getBoolean(key, false); } @Override public void setInteger(String key, int value) { editPreferences().putInt(key, value).commit(); } @Override public int getInteger(String key) { return getPreferences().getInt(key, 0); } @Override public void setFloat(String key, float value) { editPreferences().putFloat(key, value).commit(); } @Override public float getFloat(String key) { return getPreferences().getFloat(key, 0); } } 

Nota: Vuelva a colocar la clave de SharedPreference con SP_TITLE .

Ejemplos:

Cadena de la tienda en shareperence :

 setString("my_key", "my_value"); 

Obtener cadena de shareperence :

 String strValue = getString("my_key"); 

Espero que esto te ayudará.

ahorrar

 PreferenceManager.getDefaultSharedPreferences(this).edit().putString("VarName","your value").apply(); 

Para recuperarse

 String name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue"); 

Valor predeterminado es: Valores a devolver si esta preferencia no existe.

Puede cambiar " this " con getActivity () o getApplicationContext () en algunos casos

Hay muchas maneras en que la gente recomienda cómo usar SharedPreferences . He hecho un proyecto de demostración aquí . El punto clave en la muestra es utilizar el objeto ApplicationContext & single sharedpreferences . Esto demuestra cómo usar SharedPreferences con las siguientes características: –

  • Uso de la clase singelton para acceder / actualizar SharedPreferences
  • No es necesario pasar el contexto siempre para leer / escribir SharedPreferences
  • Utiliza apply () en lugar de commit ()
  • Apply () es asynchronus guardar, no devuelve nada, se actualiza el valor en la memoria primero y los cambios se escriben en el disco más tarde asynchronusly.
  • Commit () es sincronizar guardar, devolver verdadero / falso basado en el resultado. Los cambios se escriben en el disco sincrónicamente
  • Funciona en android 2.3+ versiones

Ejemplo de uso como a continuación: –

 MyAppPreference.getInstance().setSampleStringKey("some_value"); String value= MyAppPreference.getInstance().getSampleStringKey(); 

Obtenga el código fuente aquí y se pueden encontrar las API detalladas aquí en developer.android.com

 editor.putString("text", mSaved.getText().toString()); 

Aquí, mSaved puede ser cualquier textview o edittext desde donde podemos extraer una cadena. Simplemente puede especificar una cadena. Aquí el texto será la clave que contiene el valor obtenido de mSaved (TextView o Edittext).

 SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE); 

También no hay necesidad de guardar el archivo de preferencia utilizando el nombre del paquete, es decir, "com.example.app". Puedes mencionar tu nombre preferido. ¡¡Espero que esto ayude!!

Editar

 SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putString("yourValue", value); editor.commit(); 

Leer

 SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE); value= pref.getString("yourValue", ""); 

Usando esta biblioteca simple , aquí es cómo usted hace las llamadas a SharedPreferences.

 TinyDB tinydb = new TinyDB(context); tinydb.putInt("clickCount", 2); tinydb.putString("userName", "john"); tinydb.putBoolean("isUserMale", true); tinydb.putList("MyUsers", mUsersArray); tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap); //These plus the corresponding get methods are all Included 

Quería añadir aquí que la mayoría de los fragmentos para esta pregunta tendrá algo como MODE_PRIVATE cuando se utiliza SharedPreferences. Bien, MODE_PRIVATE significa que lo que escriba en esta preferencia compartida sólo puede ser leído por su aplicación.

Sea cual sea la clave que pase al método getSharedPreferences (), android crea un archivo con ese nombre y almacena los datos de preferencia en él. También recuerde que se supone que getSharedPreferences () se utiliza cuando tiene la intención de tener múltiples archivos de preferencias para su aplicación. Si tiene la intención de usar un archivo de preferencias individuales y almacenar todos los pares clave-valor en él, utilice el método getSharedPreference (). Es extraño por qué todo el mundo (incluido yo mismo) simplemente utiliza getSharedPreferences () sabor sin siquiera entender la diferencia entre los dos anteriores.

El siguiente tutorial de vídeo debería ayudar a https://www.youtube.com/watch?v=2PcAQ1NBy98

Simple y sin complicaciones :: Biblioteca "Android-SharedPreferences-Helper"

Mejor tarde que nunca: creé la biblioteca "Android-SharedPreferences-Helper" para ayudar a reducir la complejidad y el esfuerzo de usar SharedPreferences . También proporciona alguna funcionalidad extendida. Pocas cosas que ofrece son las siguientes:

  • Inicialización y configuración de una línea
  • Selección fácil de si desea usar las preferencias predeterminadas o un archivo de preferencias personalizado
  • Predefinidos (valores predeterminados de tipo de datos) y personalizables (lo que puede elegir) valores predeterminados para cada tipo de datos
  • Posibilidad de establecer un valor predeterminado diferente para un solo uso con sólo un parámetro adicional
  • Puede registrar y anular el registro OnSharedPreferenceChangeListener como lo hace para la clase predeterminada
 dependencies { ... ... compile(group: 'com.viralypatel.sharedpreferenceshelper', name: 'library', version: '1.1.0', ext: 'aar') } 

Declaración de SharedPreferencesHelper object: (recomendado a nivel de clase)

 SharedPreferencesHelper sph; 

Instanciación del objeto SharedPreferencesHelper: (recomendado en el método onCreate ()

 // use one of the following ways to instantiate sph = new SharedPreferencesHelper(this); //this will use default shared preferences sph = new SharedPreferencesHelper(this, "myappprefs"); // this will create a named shared preference file sph = new SharedPreferencesHelper(this, "myappprefs", 0); // this will allow you to specify a mode 

Poner valores en las preferencias compartidas

¡Bastante sencillo! A diferencia de la forma predeterminada (cuando se utiliza la clase SharedPreferences) NO necesitará llamar a .edit() y .commit() nunca.

 sph.putBoolean("boolKey", true); sph.putInt("intKey", 123); sph.putString("stringKey", "string value"); sph.putLong("longKey", 456876451); sph.putFloat("floatKey", 1.51f); // putStringSet is supported only for android versions above HONEYCOMB Set name = new HashSet(); name.add("Viral"); name.add("Patel"); sph.putStringSet("name", name); 

¡Eso es! Sus valores se almacenan en las preferencias compartidas.

Cómo obtener valores de las preferencias compartidas

Una vez más, sólo una llamada de método simple con el nombre de clave.

 sph.getBoolean("boolKey"); sph.getInt("intKey"); sph.getString("stringKey"); sph.getLong("longKey"); sph.getFloat("floatKey"); // getStringSet is supported only for android versions above HONEYCOMB sph.getStringSet("name"); 

Tiene mucha otra funcionalidad extendida

Compruebe los detalles de la funcionalidad extendida, el uso y las instrucciones de instalación, etc. en la página del repositorio de GitHub .

Aquí he creado una clase de ayuda para usar las preferencias en android.

Esta es la clase de ayuda:

 public class PrefsUtil { public static SharedPreferences getPreference() { return PreferenceManager.getDefaultSharedPreferences(Applicatoin.getAppContext()); } public static void putBoolean(String key, boolean value) { getPreference().edit().putBoolean(key, value) .apply(); } public static boolean getBoolean(String key) { return getPreference().getBoolean(key, false); } public static void putInt(String key, int value) { getPreference().edit().putInt(key, value).apply(); } public static void delKey(String key) { getPreference().edit().remove(key).apply(); } } 

Para almacenar y recuperar variables globales en una forma de función. Para probar, asegúrese de que tiene elementos de Textview en su página, descomente las dos líneas del código y ejecute. A continuación, comente las dos líneas de nuevo y ejecute.
Aquí el ID del TextView es nombre de usuario y contraseña.

En cada clase en la que desee utilizarla, agregue estas dos rutinas al final. Me gustaría que esta rutina fuera rutinas globales, pero no sé cómo. Esto funciona.

Los variables están disponibles en todas partes. Almacena las variables en "MyFile". Puedes cambiarlo a tu manera.

Lo llamas usando

  storeSession("username","frans"); storeSession("password","!2#4%");*** 

El nombre de usuario variable se llenará con "frans" y la contraseña con "! 2 # 4%". Incluso después de un reinicio están disponibles.

Y lo recupera usando

  password.setText(getSession(("password"))); usernames.setText(getSession(("username"))); 

Debajo de todo el código de mi grid.java

  package nl.yentel.yenteldb2; import android.content.SharedPreferences; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class Grid extends AppCompatActivity { private TextView usernames; private TextView password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_grid); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); getSupportActionBar().setDisplayHomeAsUpEnabled(true); ***// storeSession("username","[email protected]"); //storeSession("password","mijn wachtwoord");*** password = (TextView) findViewById(R.id.password); password.setText(getSession(("password"))); usernames=(TextView) findViewById(R.id.username); usernames.setText(getSession(("username"))); } public void storeSession(String key, String waarde) { SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putString(key, waarde); editor.commit(); } public String getSession(String key) { //http://androidexample.com/Android_SharedPreferences_Basics/index.php?view=article_discription&aid=126&aaid=146 SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); String output = pref.getString(key, null); return output; } } 

below you find the textview items

 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="usernames" android:id="@+id/username" android:layout_below="@+id/textView" android:layout_alignParentStart="true" android:layout_marginTop="39dp" android:hint="hier komt de username" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="password" android:id="@+id/password" android:layout_below="@+id/user" android:layout_alignParentStart="true" android:hint="hier komt het wachtwoord" /> 

I write a helper class for sharedpreferences:

 import android.content.Context; import android.content.SharedPreferences; /** * Created by mete_ on 23.12.2016. */ public class HelperSharedPref { Context mContext; public HelperSharedPref(Context mContext) { this.mContext = mContext; } /** * * @param key Constant RC * @param value Only String, Integer, Long, Float, Boolean types */ public void saveToSharedPref(String key, Object value) throws Exception { SharedPreferences.Editor editor = mContext.getSharedPreferences(key, Context.MODE_PRIVATE).edit(); if (value instanceof String) { editor.putString(key, (String) value); } else if (value instanceof Integer) { editor.putInt(key, (Integer) value); } else if (value instanceof Long) { editor.putLong(key, (Long) value); } else if (value instanceof Float) { editor.putFloat(key, (Float) value); } else if (value instanceof Boolean) { editor.putBoolean(key, (Boolean) value); } else { throw new Exception("Unacceptable object type"); } editor.commit(); } /** * Return String * @param key * @return null default is null */ public String loadStringFromSharedPref(String key) throws Exception { SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE); String restoredText = prefs.getString(key, null); return restoredText; } /** * Return int * @param key * @return null default is -1 */ public Integer loadIntegerFromSharedPref(String key) throws Exception { SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE); Integer restoredText = prefs.getInt(key, -1); return restoredText; } /** * Return float * @param key * @return null default is -1 */ public Float loadFloatFromSharedPref(String key) throws Exception { SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE); Float restoredText = prefs.getFloat(key, -1); return restoredText; } /** * Return long * @param key * @return null default is -1 */ public Long loadLongFromSharedPref(String key) throws Exception { SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE); Long restoredText = prefs.getLong(key, -1); return restoredText; } /** * Return boolean * @param key * @return null default is false */ public Boolean loadBooleanFromSharedPref(String key) throws Exception { SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE); Boolean restoredText = prefs.getBoolean(key, false); return restoredText; } } 

I have created a Helper class to make my Life easy. This is a generic class and has a-lot of methods those are commonly used in Apps like Shared Preferences, Email Validity, Date Time Format. Copy this class in your code and access it's methods wherever you need.

  import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.support.v4.app.FragmentActivity; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.Toast; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * Created by Zohaib Hassan on 3/4/2016. */ public class Helper { private static ProgressDialog pd; public static void saveData(String key, String value, Context context) { SharedPreferences sp = context.getApplicationContext() .getSharedPreferences("appData", 0); SharedPreferences.Editor editor; editor = sp.edit(); editor.putString(key, value); editor.commit(); } public static void deleteData(String key, Context context){ SharedPreferences sp = context.getApplicationContext() .getSharedPreferences("appData", 0); SharedPreferences.Editor editor; editor = sp.edit(); editor.remove(key); editor.commit(); } public static String getSaveData(String key, Context context) { SharedPreferences sp = context.getApplicationContext() .getSharedPreferences("appData", 0); String data = sp.getString(key, ""); return data; } public static long dateToUnix(String dt, String format) { SimpleDateFormat formatter; Date date = null; long unixtime; formatter = new SimpleDateFormat(format); try { date = formatter.parse(dt); } catch (Exception ex) { ex.printStackTrace(); } unixtime = date.getTime(); return unixtime; } public static String getData(long unixTime, String formate) { long unixSeconds = unixTime; Date date = new Date(unixSeconds); SimpleDateFormat sdf = new SimpleDateFormat(formate); String formattedDate = sdf.format(date); return formattedDate; } public static String getFormattedDate(String date, String currentFormat, String desiredFormat) { return getData(dateToUnix(date, currentFormat), desiredFormat); } public static double distance(double lat1, double lon1, double lat2, double lon2, char unit) { double theta = lon1 - lon2; double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta)); dist = Math.acos(dist); dist = rad2deg(dist); dist = dist * 60 * 1.1515; if (unit == 'K') { dist = dist * 1.609344; } else if (unit == 'N') { dist = dist * 0.8684; } return (dist); } /* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */ /* :: This function converts decimal degrees to radians : */ /* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */ private static double deg2rad(double deg) { return (deg * Math.PI / 180.0); } /* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */ /* :: This function converts radians to decimal degrees : */ /* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */ private static double rad2deg(double rad) { return (rad * 180.0 / Math.PI); } public static int getRendNumber() { Random r = new Random(); return r.nextInt(360); } public static void hideKeyboard(Context context, EditText editText) { InputMethodManager imm = (InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); } public static void showLoder(Context context, String message) { pd = new ProgressDialog(context); pd.setCancelable(false); pd.setMessage(message); pd.show(); } public static void showLoderImage(Context context, String message) { pd = new ProgressDialog(context); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setCancelable(false); pd.setMessage(message); pd.show(); } public static void dismissLoder() { pd.dismiss(); } public static void toast(Context context, String text) { Toast.makeText(context, text, Toast.LENGTH_LONG).show(); } /* public static Boolean connection(Context context) { ConnectionDetector connection = new ConnectionDetector(context); if (!connection.isConnectingToInternet()) { Helper.showAlert(context, "No Internet access...!"); //Helper.toast(context, "No internet access..!"); return false; } else return true; }*/ public static void removeMapFrgment(FragmentActivity fa, int id) { android.support.v4.app.Fragment fragment; android.support.v4.app.FragmentManager fm; android.support.v4.app.FragmentTransaction ft; fm = fa.getSupportFragmentManager(); fragment = fm.findFragmentById(id); ft = fa.getSupportFragmentManager().beginTransaction(); ft.remove(fragment); ft.commit(); } public static AlertDialog showDialog(Context context, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(message); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // TODO Auto-generated method stub } }); return builder.create(); } public static void showAlert(Context context, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Alert"); builder.setMessage(message) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }).show(); } public static boolean isURL(String url) { if (url == null) return false; boolean foundMatch = false; try { Pattern regex = Pattern .compile( "\\b(?:(https?|ftp|file)://|www\\.)?[-A-Z0-9+&#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]\\.[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); Matcher regexMatcher = regex.matcher(url); foundMatch = regexMatcher.matches(); return foundMatch; } catch (PatternSyntaxException ex) { // Syntax error in the regular expression return false; } } public static boolean atLeastOneChr(String string) { if (string == null) return false; boolean foundMatch = false; try { Pattern regex = Pattern.compile("[a-zA-Z0-9]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); Matcher regexMatcher = regex.matcher(string); foundMatch = regexMatcher.matches(); return foundMatch; } catch (PatternSyntaxException ex) { // Syntax error in the regular expression return false; } } public static boolean isValidEmail(String email, Context context) { String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[AZ]{2,4}$"; CharSequence inputStr = email; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); if (matcher.matches()) { return true; } else { // Helper.toast(context, "Email is not valid..!"); return false; } } public static boolean isValidUserName(String email, Context context) { String expression = "^[0-9a-zA-Z]+$"; CharSequence inputStr = email; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); if (matcher.matches()) { return true; } else { Helper.toast(context, "Username is not valid..!"); return false; } } public static boolean isValidDateSlash(String inDate) { SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy"); dateFormat.setLenient(false); try { dateFormat.parse(inDate.trim()); } catch (ParseException pe) { return false; } return true; } public static boolean isValidDateDash(String inDate) { SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy"); dateFormat.setLenient(false); try { dateFormat.parse(inDate.trim()); } catch (ParseException pe) { return false; } return true; } public static boolean isValidDateDot(String inDate) { SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy"); dateFormat.setLenient(false); try { dateFormat.parse(inDate.trim()); } catch (ParseException pe) { return false; } return true; } } 
  • Android Preferences error, "String no se puede convertir en int"
  • Cómo guardar la lista <Object> a SharedPreferences?
  • ¿Cómo puedo almacenar un HashMap <Integer, String> en android usando preferencias compartidas?
  • SharedPreferences: ¿Es una clase o una interfaz?
  • Cómo cambiar el valor de preferencia compartida de Android de String a Int
  • Loader onLoadFinished () no se llama
  • Configuración de usuario guardada en SharedPreferences eliminada o perdida entre recargas de la aplicación
  • Primera vez que se muestra Solución de actividad
  • Android M extraño problema de preferencias compartidas
  • ¿Dónde se almacenan las preferencias compartidas?
  • Diferencia entre las preferencias compartidas y los proveedores de contenido en android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.