Iam prova a creare un correttore e voglio salvare un valore in SharedPreferences. Ma I'am non è sicuro se funzionaSharedPreferences Cancella/Salva
Questo quello che faccio per salvare il valore è: *
SharedPreferences prefs = getSharedPreferences("PREFERENCE", MODE_PRIVATE);
boolean firstrun = prefs.getBoolean("firstrun", true);
db = openOrCreateDatabase("value.db", Context.MODE_PRIVATE, null); // optional CursorFactory
if (firstrun) {
SharedPreferences.Editor editor = prefs.edit();
db.execSQL("CREATE TABLE startValue (ID Integer Primary Key, myValue Integer)");
db.execSQL("INSERT INTO startValue (myValue) VALUES (2)");
editor.putBoolean("firstrun", false);
editor.apply();
}
// Save the state
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.edit()
.putBoolean("firstrun", false)
.commit();
e per azzerare i preferenece da un'altra attività è:
try{
db = openOrCreateDatabase("value.db", Context.MODE_PRIVATE, null); // optional CursorFactory
db.execSQL("DROP TABLE IF EXISTS startValue");
db.close();
SharedPreferences preferences = getPreferences(0);
SharedPreferences.Editor editor = preferences.edit();
editor.remove("firstrun");
editor.clear();
editor.commit();
this.finish();
}
catch(SQLException ex)
{
//catch error here
}
Problema
Ma quando I'am testando come vedo non chiarire le preferenze. Sto facendo qualcosa di sbagliato o?
SharedPreferences preferenze = getSharedPreferences ("Preference", 0); dovrei cambiare "PREFERENCE" in "firstrun" o? – Tirolel
No.Questo codice cancellerà tutte le SharedPreferences. – AwadKab
Grazie, questo è utile, ma come cancellare una parte di sharedPreferences? – alicanbatur