First I want to describe my situation briefly.开发者_如何学JAVA
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
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);
Here is my solution 1.my app can not use.
import androidx.appcompat.app.AppCompatActivity;
SharedPreferences settings = new AppCompatActivity().getSharedPreferences(PREFERENCES, 0);
2.works fine in my app
public static boolean isLoggedIn(AppCompatActivity activity) {
final SharedPreferences loggedSP = activity.getSharedPreferences(SP_name.get_Logged_SPname(), MODE_PRIVATE);
return loggedSP.getBoolean(SP_name.get_Logged_SPkey(),false);
}
to execute it in my main activity
boolean a = LoginRepository.isLoggedIn(this);
精彩评论