Come posso archiviare permanentemente un valore da una schermata di preferenza?
-
27-10-2019 - |
Domanda
Sono un principiante in Android e sto solo cercando di conservare permanentemente una corda.
Voglio ottenere questa stringa da un PreferenceActivity
e quindi aggiornare il testo di a TextView
.
Stavo leggendo le opzioni disponibili per l'archiviazione persistente: http://developer.android.com/guide/topics/data/data-sorage.html#pref
Ho provato a usare SharedPreferences
Ma non è molto chiaro per me su come dovrebbe funzionare.
Ho creato un'app di test molto semplice.
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();
}
}
Preferenze.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>
Il testo del TextView
Non cambia mai, è sempre impostato sul valore che ho impostato su strings.xml.
Potete per favore aiutarmi a capire cosa sto facendo di sbagliato?
Grazie mille.
Soluzione
Sei estremamente vicino a quello che consiglierei:
1) Definire alcune preferenze condivise:
public static final String MY_PREFERENCES = "MyPreferences";
...
public static final SOME_PREFERENCE = "SomePreference";
2) Leggi dalle preferenze condivise
SharedPreferences myPreferences;
...
myPreferences = getSharedPreferences (MY_PREFERENCES, Context.MODE_PRIVATE);
3) Salva/aggiorna una preferenze condivise:
Editor editor = myPreferences.edit ();
editor.putString (SOME_PREFERENCE, "abc");
editor.commit ();
Altri suggerimenti
Esempio rapido di salvare/scrivere nome utente, password in preferenze.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = preferences.edit();
edit.putString("username", "abcd");
edit.putString("password", "abcd#");
edit.commit();
Esempio rapido della lettura del nome utente, della password dalle preferenze.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String strUsername = preferences.getString("username", null);
String strPassword = preferences.getString("password", null);
Ho appena realizzato il mio codice correlato a SharedPreferences
è corretto, ma il TextView
non si aggiorna mai perché ho provato a modificare direttamente la stringa stessa, non il TextView
!
Appena risolto in questo modo:
/* Update text of TextView */
TextView t = (TextView) this.findViewById(R.id.name);
// previously was R.string.name - not correct!
t.setText(name);
Molte grazie per il tuo aiuto ragazzi :)