Reputation: 21
public class User extends Activity implements UserI {
private SharedPreferences sharedPref;
private Context mcontext;
private boolean isNotificationsOn;
public User(Context context) {
mcontext = context;
Load();
}
public void Load () {
//app crashes
sharedPref = PreferenceManager.getDefaultSharedPreferences(mcontext);
isNotificationsOn = sharedPref.getBoolean("switch_recieveNotifications", false);
}
}
public class SettingsActivity extends
AppCompatPreferenceActivity {
...
public static class GeneralPreferenceFragment extends
PreferenceFragment {
...
}
}
Hi everyone,
I'm a new android app developer, and I would really appreciate your help.
My app crashes every time I call: PreferenceManager.getDefaultSharedPreferences(context).
I have tried different strategies after reading a few answers related, such as:
it all produces the same result- crashing app
I'm lost :/ would love to get your insights
Upvotes: 0
Views: 235
Reputation: 5392
An Activity is the context, it represents the controller for the view. So your Load should happen either in the onCreate or onResume method.
Then your context should be the keyword "this". You should also consider naming it UserActivity so it is obvious what you are doing. Lastly in Java or Kotlin we start with lowercase method names.
@Override
public void onCreate(Bundle savedInstanceState) {
load()
}
private void load(){
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
isNotificationsOn = sharedPref.getBoolean("switch_recieveNotifications", false);
}
That will get you running again. Then make sure you are starting your activity properly and not trying to build your own constructor. Simply use
startActivity(this, new Intent(this, UserActivity));
Upvotes: 1