When I created a shared preferences on the head of the activity, my app fails on run time. On the other hand when I put the shared preferences inside a method than the app runs smoothly. I want to put the shared preferences on the top of the class so I will not have to create the shared preferences in every single method.
Why can't I create shared preferences globally? Now that I understand that I cant create the shared preferences as a global object, is there a way that I will not have to create the shared preferences on every method?
Assuming you mean initializing it at global scope in an Activity- because an Activity is not a valid Context until onCreate is called on it. At the time the constructor is called (which is when those variables are initialized) the class isn't set up with all the data needed to be valid, so using it as a Context will lead to a crash.