RESOLVED! Shared Preference Context Error

During android development, especially for a beginner like me the creepiest thing which I felt was Handling Contexts. Shared preferences is really a cool thing if we want to save some handy information by the user on a device even if an app is killed. BUT context exceptions are everywhere.

So here we will not go deep into context understanding or preferences documentations. We will only discuss the best approach to use Shared Preference in application from anywhere inside your app. Using this method you can SET or GET preference literally from anywhere

– Mainactivity
– Non-Mainactivity
– Services
– Broadcasts

etc etc.

Let’s Begin with code.

Step 1) Create a new app with MainActivity.

Step 2) In MainActivity add below line of code to above OnCreate method.

 

Step 3) Get instance of getSharedPreferences method providing name and MODE.

 

Step 4) Now we will create a new Class “PreferenceHelper” having getter and setters for preferences.

Our “PreferenceHelper” Class will look like this

 

Step 5) Let’s create an Input and a Button to save a value in preferences.

After some drag-drop in activity-layout added a text input and a button which will look like this.

 

You can try to save Entered Name. It will Show up on top and will reappear even if you kill and reopen the app.

Find source code in Google Drive here

Complete Files will Look like:

MainActivity.java

 

 

PreferenceHelper.java

 

 

activity_main.xml

 

 

content_main.xml

 

 

AndroidManifest.xml