Reputation: 31
I've come across an issue with trying to append a settings preference string onto another string I have.
Currently I have:
public class MyApp extends Application {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
public static final String USER_LOGIN = "https://example.com";
@Override
public void onCreate(){
super.onCreate();
myFunction(USER_LOGIN);
}
What I'm trying to achieve this with:
public class MyApp extends Application {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
public static final String USER_LOGIN = "https://" + preferences.getString(SettingsFragment.USER_SITE, "");
@Override
public void onCreate(){
super.onCreate();
myFunction(USER_LOGIN);
}
However, Android Studio is telling me "non-static field 'preferences' cannot be referenced from a static context". How would I be able to reference this field?
Upvotes: 0
Views: 66
Reputation: 2512
Just assign them inside onCreate
:
public class MyApp extends Application {
SharedPreferences preferences;
private String USER_LOGIN;
@Override
public void onCreate(){
super.onCreate();
preferences = PreferenceManager.getDefaultSharedPreferences(this);
USER_LOGIN = "https://" + preferences.getString(SettingsFragment.USER_SITE, "");
myFunction(USER_LOGIN);
}
}
Upvotes: 0
Reputation: 474
Is your function in the same activity? If yes try not to pass the static var? Instead access it directly in the "myfunction".. I see no point to call that way and make it static at the same time.
Upvotes: 0
Reputation: 136
Since "SharedPreferences preferences" is a Object's member, it can not be used by a static member. So change :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
to
static SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Upvotes: 1