I’m about 6 weeks into learning Java and still struggling with implementing static methods (thought I really understood it, but this proved me wrong!).
I’m trying to make the value of a locally stored key-value pair available publicly. Here’s my initial code:
public class Settings extends Activity implements OnClickListener {
public Settings(TextView loginText, TextView passwdText) {
super();
this.loginText = loginText;
this.passwdText = passwdText;
}
public static String getDriverNum() {
SharedPreferences sp = getSharedPreferences(DELEX_SP, MODE_PRIVATE); <---ERROR
String Login = sp.getString("KeyLgn", "No Login Found");
return Login;
}
Of course, I get an error “Cannot make a static reference to the non-static method getSharedPreferences(String, int) from the type ContextWrapper”, so I try to wrap the non-static method in my own public method, as a similar StackOverflow answer indicated:
public class Settings extends Activity implements OnClickListener {
public Settings(TextView loginText, TextView passwdText) {
super();
this.loginText = loginText;
this.passwdText = passwdText;
}
public static String getDriverNum() {
String Login = getSharedPref().getString("KeyLgn", "No Login Found"); <-- SAME ERROR
return Login;
}
public SharedPreferences getSharedPref() {
SharedPreferences sp = getSharedPreferences(DELEX_SP, MODE_PRIVATE);
return sp;
}
But this just caused the same error as I haven’t resolved the call to the non-static getSharedPreferences method. What’s the best way to resolve this? Is it to create a class that wraps getSharedPreferences instead?
Thanks for your patience while I struggle with static nomenclature.
If you want to write a static method that utilizes non-static methods, you just pass an instance to it like this:
So what you’re doing is a great pattern. I use it all the time for “helpers” that can be reused across many classes (aka composition) Just make your “SomeObject” the Context.
Here’s the pattern I use in Android to get a nice central point to define default preferences:
…
This pattern allows the definition of default values to be in one place.