Search code examples
databaseandroidandroid-preferences

Problems calling Android's getSharedPreferences(); from SQLiteOpenHelper class


First I want to describe my situation briefly.

I have two classes, one MainClass and one DataBaseHelper class, which extends SQLiteOpenHelper.

From my MainClass I call a method in the DataBaseHelper class to open a data base. Before opening the data base I want to check the users data base version (this is important as soon as I want to update the data base and push it to the Android market). So from the DataBaseHelper class I call the following method, which is in the MainClass.

 public int checkCurrentDbVersion(){
        // Restore preferences
        SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
        int dbUpgradeVar = settings.getInt("dbUpgradeVar", 1);
        return dbUpgradeVar;        
    }

I call the checkCurrentDbVersion() method from the DataBaseHelper class like so:

    MainClass currentDbVersion = new MainClass(); 

    int oldDbVersion = currentDbVersion.checkCurrentDbVersion();

As soon as the debugger runs the following line, it stops.

SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);

What am I doing wrong? I have no constructor defined. Could that be the failure?

Best Regards Johe


Solution

  • I found a solution, which I wanna share. It can be found here:

    Passing data through intents instead of constructors

    I forgot the context (I am still not 100% sure what the context is all about, but anyways...).

    So to get the code working I changed it like so:

     public int checkCurrentDbVersion(Context context){
            // Restore preferences
            SharedPreferences settings = context.getSharedPreferences(PREFERENCES, 0);
            int dbUpgradeVar = settings.getInt("dbUpgradeVar", 1);
            return dbUpgradeVar;        
        }
    

    Call the method

    private final Context myContext;
    
    /*
    *do some other stuff here
    */
    
        MainClass currentDbVersion = new MainClass(); 
    
        int oldDbVersion = currentDbVersion.checkCurrentDbVersion(myContext);