¿Cómo puedo almacenar permanentemente un valor de una pantalla de preferencias?
-
27-10-2019 - |
Pregunta
Soy un novato en Android y solo estoy tratando de almacenar permanentemente una cadena.
Quiero obtener esta cadena de un PreferenceActivity
y luego actualice el texto de un TextView
.
Estaba leyendo sobre las opciones disponibles para el almacenamiento persistente: http://developer.android.com/guide/topics/data/data-storage.html#pref
He intentado usar SharedPreferences
Pero no es muy claro para mí sobre cómo debería funcionar.
He creado una aplicación de prueba muy simple.
MainActivity.java
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
/* method that starts preferences */
public void openPreferences(View v) {
Intent i = new Intent(this, Preferences.class);
startActivity(i);
}
@Override
protected void onStart(){
super.onStart();
// Get preferences
SharedPreferences preferences = getPreferences(0);
String name = preferences.getString("name","Empty string!");
// Create a RemoteViews layout
RemoteViews views = new RemoteViews(getPackageName(),R.layout.main);
// set new text for labels
views.setTextViewText(R.string.name, name);
}
@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences preferences = getPreferences(0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("name", "This is a test");
// Commit the edits!
editor.commit();
}
}
Preferencias.java
public class Preferences extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Androidmanifest.xml
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Preferences"
android:label="@string/preferences_title">
</activity>
</application>
El texto del TextView
Nunca cambia, siempre se establece en el valor que configuré en Strings.xml.
¿Puedes ayudarme a entender qué estoy haciendo mal?
Muchísimas gracias.
Solución
Estás extremadamente cerca de lo que recomendaría:
1) Defina algunas preferencias compartidas:
public static final String MY_PREFERENCES = "MyPreferences";
...
public static final SOME_PREFERENCE = "SomePreference";
2) Leer de preferencias compartidas
SharedPreferences myPreferences;
...
myPreferences = getSharedPreferences (MY_PREFERENCES, Context.MODE_PRIVATE);
3) Guardar/actualizar las preferencias compartidas:
Editor editor = myPreferences.edit ();
editor.putString (SOME_PREFERENCE, "abc");
editor.commit ();
Otros consejos
Ejemplo rápido de guardar/escribir nombre de usuario, contraseña en preferencias.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = preferences.edit();
edit.putString("username", "abcd");
edit.putString("password", "abcd#");
edit.commit();
Ejemplo rápido de lectura de nombre de usuario, contraseña de preferencias.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String strUsername = preferences.getString("username", null);
String strPassword = preferences.getString("password", null);
Me acabo de dar cuenta de mi código relacionado con SharedPreferences
es correcto, pero el TextView
nunca se actualiza porque intenté editar directamente la cadena en sí, no la TextView
!
Acabo de resolver de esta manera:
/* Update text of TextView */
TextView t = (TextView) this.findViewById(R.id.name);
// previously was R.string.name - not correct!
t.setText(name);
Muchas gracias por tu ayuda chicos :)