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

 

 

 

 

 

 

 

Thanks for visiting :) Let me know if you have some suggestions or feedback for this post in the comment section. Looking for any tutorial or demo on FreakyJolly, just drop me a message here

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
kindacinic Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
kindacinic
Guest
kindacinic

This is pretty ugly my dude, you depend on a static variable that you init on MainActivity, what happens if your code calls this PreferenceHelper after an async operation and preferences static variable has been cleared?? With all my respect this is a bad approach.