usuario3104719
Tengo tres actividades A, B y C donde A y B son formularios y después de completar y guardar los datos del formulario en la base de datos (SQLite). Estoy usando la intención de A a B y luego de B a C. Lo que quiero es que cada vez que abra mi aplicación quiero C como mi pantalla de inicio y ya no A y B.
Supongo que las preferencias compartidas funcionarían para esto, pero no puedo encontrar un buen ejemplo que me dé un punto de partida.
Jorgesys
Configuración de valores 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.apply();
Recuperar datos de preferencia:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
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:
-
Considere usar apply() en su lugar; commit escribe sus datos en el almacenamiento persistente inmediatamente, mientras que apply los manejará en segundo plano.
– Código Ninja
2 mayo 2015 a las 21:51
-
apply()
es una llamada asíncrona para realizar E/S de disco donde comocommit()
es sincrónico. Así que evita llamarcommit()
del subproceso de la interfaz de usuario.– Aniket Thakur
10 de noviembre de 2015 a las 8:55
-
Gracias hombre, usé tu código en mis múltiples proyectos.
– Tariq Mahmud
12 de julio de 2020 a las 3:36
Krausz Lóránt Szilveszter
Crear preferencias compartidas
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
Almacenamiento de datos como par CLAVE/VALOR
editor.putBoolean("key_name1", true); // Saving boolean - true/false
editor.putInt("key_name2", "int value"); // Saving integer
editor.putFloat("key_name3", "float value"); // Saving float
editor.putLong("key_name4", "long value"); // Saving long
editor.putString("key_name5", "string value"); // Saving string
// Save the changes in SharedPreferences
editor.apply(); // commit changes
Obtener datos de SharedPreferences
// Si el valor de la clave no existe, devuelva el valor del segundo parámetro; en este caso, nulo
boolean userFirstLogin= pref.getBoolean("key_name1", true); // getting boolean
int pageNumber=pref.getInt("key_name2", 0); // getting Integer
float amount=pref.getFloat("key_name3", null); // getting Float
long distance=pref.getLong("key_name4", null); // getting Long
String email=pref.getString("key_name5", null); // getting String
Eliminación del valor clave de SharedPreferences
editor.remove("key_name3"); // will delete key key_name3
editor.remove("key_name4"); // will delete key key_name4
// Save the changes in SharedPreferences
editor.apply(); // commit changes
Borrar todos los datos de SharedPreferences
editor.clear();
editor.apply(); // commit changes
-
pref.getBoolean(“nombre_clave1”, nulo); no puede ser nulo. Necesita un valor predeterminado si no hay nada almacenado.
– Boris Karloff
26 de diciembre de 2014 a las 14:36
-
Será mejor que uses apply() en lugar de commit(). apply() es asíncrono y lo ejecutará en un hilo de fondo
– Androide
1 de febrero de 2016 a las 10:49
-
Se bloqueará si key_name3 o key_name4 son nulos
– TacB0sS
14 mayo 2017 a las 21:51
-
Tengo una página de registro que almacena información del usuario y tengo una página de inicio de sesión en la que el usuario inicia sesión con esa información. Tengo dos clases, tomo información de una clase y quiero usar esa información en otra clase. Cuando uso el código anterior en mi código. Tomo una excepción de puntero nulo. ¿Hay un uso como yo? @KrauszLórántSzilveszter
– ZpCikTi
18 de noviembre de 2017 a las 11:34
omi chispitas
¿Cómo inicializar?
// 0 - for private mode`
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
¿Cómo almacenar datos en preferencias compartidas?
editor.putString("key_name", "string value"); // Storing string
O
editor.putInt("key_name", "int value"); //Storing integer
Y no olvides aplicar:
editor.apply();
¿Cómo recuperar datos de preferencias compartidas?
pref.getString("key_name", null); // getting String
pref.getInt("key_name", 0); // getting Integer
Espero que esto te ayude 🙂
-
La inicialización es importante si accede en una actividad, fragmento o clase pública
– Fuego de Dragon
16 de noviembre de 2019 a las 11:50
Puede crear su clase SharedPreference personalizada
public class YourPreference {
private static YourPreference yourPreference;
private SharedPreferences sharedPreferences;
public static YourPreference getInstance(Context context) {
if (yourPreference == null) {
yourPreference = new YourPreference(context);
}
return yourPreference;
}
private YourPreference(Context context) {
sharedPreferences = context.getSharedPreferences("YourCustomNamedPreference",Context.MODE_PRIVATE);
}
public void saveData(String key,String value) {
SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
prefsEditor .putString(key, value);
prefsEditor.commit();
}
public String getData(String key) {
if (sharedPreferences!= null) {
return sharedPreferences.getString(key, "");
}
return "";
}
}
Puede obtener una instancia de YourPrefrence como:
YourPreference yourPrefrence = YourPreference.getInstance(context);
yourPreference.saveData(YOUR_KEY,YOUR_VALUE);
String value = yourPreference.getData(YOUR_KEY);
RM
Acabo de encontrar todos los ejemplos anteriores demasiado confusos, así que escribí el mío. Los fragmentos de código están bien si sabes lo que estás haciendo, pero ¿qué pasa con las personas como yo que no lo saben?
¿Quiere una solución de cortar y pegar en su lugar? ¡Pues aquí está!
Cree un nuevo archivo java y llámelo Keystore. Luego pega este código:
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
public class Keystore { //Did you remember to vote up my example?
private static Keystore store;
private SharedPreferences SP;
private static String filename="Keys";
private Keystore(Context context) {
SP = context.getApplicationContext().getSharedPreferences(filename,0);
}
public static Keystore getInstance(Context context) {
if (store == null) {
Log.v("Keystore","NEW STORE");
store = new Keystore(context);
}
return store;
}
public void put(String key, String value) {//Log.v("Keystore","PUT "+key+" "+value);
Editor editor = SP.edit();
editor.putString(key, value);
editor.commit(); // Stop everything and do an immediate save!
// editor.apply();//Keep going and save when you are not busy - Available only in APIs 9 and above. This is the preferred way of saving.
}
public String get(String key) {//Log.v("Keystore","GET from "+key);
return SP.getString(key, null);
}
public int getInt(String key) {//Log.v("Keystore","GET INT from "+key);
return SP.getInt(key, 0);
}
public void putInt(String key, int num) {//Log.v("Keystore","PUT INT "+key+" "+String.valueOf(num));
Editor editor = SP.edit();
editor.putInt(key, num);
editor.commit();
}
public void clear(){ // Delete all shared preferences
Editor editor = SP.edit();
editor.clear();
editor.commit();
}
public void remove(){ // Delete only the shared preference that you want
Editor editor = SP.edit();
editor.remove(filename);
editor.commit();
}
}
Ahora guarde ese archivo y olvídese de él. Ya terminaste con eso. Ahora vuelve a tu actividad y utilízala así:
public class YourClass extends Activity{
private Keystore store;//Holds our key pairs
public YourSub(Context context){
store = Keystore.getInstance(context);//Creates or Gets our key pairs. You MUST have access to current context!
int= store.getInt("key name to get int value");
string = store.get("key name to get string value");
store.putInt("key name to store int value",int_var);
store.put("key name to store string value",string_var);
}
}
-
Uso esta clase en mi proyecto e inicio mis preferencias compartidas en BaseActivity, y la uso en otras actividades (splashScreen, inicio de sesión y actividad principal) para verificar el estado de inicio de sesión del usuario y salir de la aplicación. ¡Pero esto no funciona para Android 8 para salir! ¿Tiene alguna sugerencia?
– roghayeh hosseini
13 de mayo de 2019 a las 7:02
Jéwôm’
Shared Preferences
son archivos XML para almacenar datos primitivos privados en pares clave-valor. Los tipos de datos incluyen Booleanos, flota, enteros, pantalones largosy instrumentos de cuerda.
Cuando queremos guardar algunos datos a los que se puede acceder a través de la aplicación, una forma de hacerlo es guardarlos en una variable global. Pero desaparecerá una vez que se cierre la aplicación. Otra forma recomendada es ahorrar en SharedPreference
. Se puede acceder a los datos guardados en el archivo SharedPreferences en toda la aplicación y persisten incluso después de que la aplicación se cierra o se reinicia.
Preferencias compartidas guarda los datos en un par clave-valor y se puede acceder a ellos de la misma manera.
Puede crear Objeto de SharedPreferences
utilizando dos métodos,
1).getSharedPreferences() : Usando estos métodos puede crear Múltiples Preferencias Compartidas y sus primeros parámetros en nombre de SharedPreferences
.
2).obtenerPreferencias() : Con este método puede crear Single SharedPreferences
.
Almacenamiento de datos
Agregar una declaración de variable/ Crear archivo de preferencias
public static final String PREFERENCES_FILE_NAME = "MyAppPreferences";
Recuperar un identificador de nombre de archivo (usando getSharedPreferences)
SharedPreferences settingsfile= getSharedPreferences(PREFERENCES_FILE_NAME,0);
Abrir editor y agregar pares clave-valor
SharedPreferences.Editor myeditor = settingsfile.edit();
myeditor.putBoolean("IITAMIYO", true);
myeditor.putFloat("VOLUME", 0.7)
myeditor.putInt("BORDER", 2)
myeditor.putLong("SIZE", 12345678910L)
myeditor.putString("Name", "Amiyo")
myeditor.apply();
No olvide aplicar/guardar usando myeditor.apply()
como se muestra arriba.
Recuperando datos
SharedPreferences mysettings= getSharedPreferences(PREFERENCES_FILE_NAME, 0);
IITAMIYO = mysettings.getBoolean("IITAMIYO", false);
//returns value for the given key.
//second parameter gives the default value if no user preference found
// (set to false in above case)
VOLUME = mysettings.getFloat("VOLUME", 0.5)
//0.5 being the default value if no volume preferences found
// and similarly there are get methods for other data types
-
Uso esta clase en mi proyecto e inicio mis preferencias compartidas en BaseActivity, y la uso en otras actividades (splashScreen, inicio de sesión y actividad principal) para verificar el estado de inicio de sesión del usuario y salir de la aplicación. ¡Pero esto no funciona para Android 8 para salir! ¿Tiene alguna sugerencia?
– roghayeh hosseini
13 de mayo de 2019 a las 7:02
Jorgesys
public class Preferences {
public static final String PREF_NAME = "your preferences name";
@SuppressWarnings("deprecation")
public static final int MODE = Context.MODE_WORLD_WRITEABLE;
public static final String USER_ID = "USER_ID_NEW";
public static final String USER_NAME = "USER_NAME";
public static final String NAME = "NAME";
public static final String EMAIL = "EMAIL";
public static final String PHONE = "PHONE";
public static final String address = "address";
public static void writeBoolean(Context context, String key, boolean value) {
getEditor(context).putBoolean(key, value).commit();
}
public static boolean readBoolean(Context context, String key,
boolean defValue) {
return getPreferences(context).getBoolean(key, defValue);
}
public static void writeInteger(Context context, String key, int value) {
getEditor(context).putInt(key, value).commit();
}
public static int readInteger(Context context, String key, int defValue) {
return getPreferences(context).getInt(key, defValue);
}
public static void writeString(Context context, String key, String value) {
getEditor(context).putString(key, value).commit();
}
public static String readString(Context context, String key, String defValue) {
return getPreferences(context).getString(key, defValue);
}
public static void writeFloat(Context context, String key, float value) {
getEditor(context).putFloat(key, value).commit();
}
public static float readFloat(Context context, String key, float defValue) {
return getPreferences(context).getFloat(key, defValue);
}
public static void writeLong(Context context, String key, long value) {
getEditor(context).putLong(key, value).commit();
}
public static long readLong(Context context, String key, long defValue) {
return getPreferences(context).getLong(key, defValue);
}
public static SharedPreferences getPreferences(Context context) {
return context.getSharedPreferences(PREF_NAME, MODE);
}
public static Editor getEditor(Context context) {
return getPreferences(context).edit();
}
}
**** Use Preferencias para escribir valor usando: – ****
Preferences.writeString(getApplicationContext(),
Preferences.NAME, "dev");
**** Use Preferencias para leer el valor usando: – ****
Preferences.readString(getApplicationContext(), Preferences.NAME,
"");
Uso de preferencias compartidas del sitio de desarrollo de Android.
– Onik
12 de abril de 2014 a las 1:06
¿Viste el tutorial oficial en developer.android.com/guide/topics/data/data-storage.html#pref ?
– Nexo axiomático
12 de abril de 2014 a las 1:07