I'm passing a string between activities with sharedPref. I'm trying to make my code more effective, and I have a wierd problem that I can't figure out.
My code in MainActivity.class :
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
//if statement for the first run of the app, else statement uses the defined city.
if (SharedPref.getCity().equals("")) {
} else {
cityText = (TextView) findViewById(R.id.prefCity);
cityText.setText(SharedPref.getCity());
}
my SharedPref.java :
public class SharedPref {
private static SharedPreferences mSharedPreferences;
//sharedPref Manager.
public SharedPref(final Context context) {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public static void setCity(String item) {
mSharedPreferences.edit().putString("city", item).apply();
}
public static String getCity() {
return mSharedPreferences.getString("city", "");
}
}
as you can see, in my MainActivity.class I am accessing the data thru "SharedPref.getCity()". meaning directly from the class, that's why I used static methods. yet the app crashes. wierd thing is, if I initialize my sharedpref in MainActivity like this:
SharedPref sharedPref = new SharedPref(getBaseContext());
then the app works just fine, even tho sharedPref is a variable that isn't used even once!
what am I missing?
p.s here's my logcat pic :
Thank you in advance for your help.