mardi 26 avril 2016

Saving the version of my database in SharedPreferences

I'm trying to add a version to my database. I followed this answer to do so. Problem is, every time I call GetDefaultSharedPreferences, it doesn't seem to find the version I stored. Here's my code:

public Database() {
    var dbPath = DatabasePath;
    int dbVersion;

    ISharedPreferences sharedPrefs = PreferenceManager.GetDefaultSharedPreferences (Application.Context);
    dbVersion = sharedPrefs.GetInt ("db_ver", 0);

    if (!File.Exists (dbPath) || dbVersion != DATABASE_VERSION) {
        CreateDatabase (dbPath);
    }

    database = new SQLiteConnection (dbPath);
}

void CreateDatabase(string dbPath) {
    var s = Application.Context.Assets.Open (originalDBLocation);
    var writeStream = new FileStream (dbPath, FileMode.OpenOrCreate, FileAccess.Write);
    ReadWriteStream (s, writeStream);
    writeStream.Close ();
    ISharedPreferences sharedPrefs = PreferenceManager.GetDefaultSharedPreferences (Application.Context);
    ISharedPreferencesEditor editor = sharedPrefs.Edit ();
    editor.PutInt ("db_ver", DATABASE_VERSION);
    editor.Commit();
}

When I run the code for the first time after building, dbVersionis always 0. Doesn't matter if I change DATABASE_VERSIONor not. When I close the app on my phone and open it again, the right version is put into dbVersion. So I guess the shared preferences get deleted when the app is reinstalled? This isn't the case in the rest of my app where I use them.

Does ayone know how I can fix this?

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire