How to get SharedPreference from non activity class for non activity - java

In my Activity class I store some data in a Sharedpreference. My non Activity class has getter and setter to read the Sharedpreference data. I want use this Data in an another Activity class. But I get always a Nullpointer exception.
This is a Code snippet from my Activity class.
SharedPreferences prefs;
prefs = getActivity().getSharedPreferences(KEY_NAME_FOR_PREF, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", name.getText().toString());
editor.commit();
This is my first non Activity class
private String name;
private Context mContext;
public PdfConsultantContacts(Context context){
mContext = context;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
And this is my second non Activity class.
Context mContext;
PdfConsultantContacts contact = new PdfConsultantContacts(mContext);
void initContact() {
SharedPreferences prefs = mContext.getApplicationContext().
getSharedPreferences("app_prefs", 0);
contact.setName(prefs.getString("name", null));
}
When I try to contact.getName(); I get always a Nullpointer exception, but I know that the SharedPreference are saved correctly.

Create a class with two static methods and use this throughout your application to store and retrieve data from SharedPreferences.
public class Utils {
public static void putStringInPreferences(Context context, String value, String key, String pKey) {
SharedPreferences sharedPreferences = context.getSharedPreferences(pKey, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public static String getStringFromPreferences(Context context,String defaultValue, String key, String pKey) {
SharedPreferences sharedPreferences = context.getSharedPreferences(pKey, Context.MODE_PRIVATE);
String temp = sharedPreferences.getString(key, defaultValue);
return temp;
}
}

Make sure "Code snippet" from your Activity is really executed, you can verify it by print some log.
Make sure the KEY_NAME_FOR_PREF equals "app_prefs".

Related

Custom SharedPreferences class

I am new to android and learning. I have theme changing option in my application from where the user can switch themes. I was using a global variable for saving theme number in the app but it was getting a loss when application get cleared from the background. So I have thought for use SharedPreferences for this purpose. I have found one simple and easy way to store and retrieve SharedPreference from here.
My code is like below :
public class Keystore {
private static Keystore store;
private SharedPreferences SP;
private static String filename="Keys";
public static int theme=1;
private Keystore(Context context) {
SP = context.getApplicationContext().getSharedPreferences(filename,0);
}
public static Keystore getInstance(Context context) {
if (store == null) {
store = new Keystore(context);
}
return store;
}
public void put(String key, String value) {
SharedPreferences.Editor editor;
editor = SP.edit();
editor.putString(key, value);
editor.apply();
}
public String get(String key) {
return SP.getString(key, null);
}
public int getInt(String key) {
return SP.getInt(key, 0);
}
public void putInt(String key, int num) {
SharedPreferences.Editor editor;
editor = SP.edit();
editor.putInt(key, num);
editor.apply();
}
public void clear(){
SharedPreferences.Editor editor;
editor = SP.edit();
editor.clear();
editor.apply();
}
public void remove(){
SharedPreferences.Editor editor;
editor = SP.edit();
editor.remove(filename);
editor.apply();
}
}
And as per example given in original answer, I am trying to use it in my activity class like below for getting value
int theme= store.getInt("theme");
Log.d(getClass().getName(),"theme"+theme);
But it's returning 0 instead of 1. I have also doubt that I have saved default value as 1 in that class like public static int theme=1; This is the correct way for saving default value in SharedPreferences?
Thanks
You should use commit ()
Commit your preferences changes back from this Editor to the
SharedPreferences object it is editing. This atomically performs the
requested modifications, replacing whatever is currently in the
SharedPreferences.
public void putInt(String key, int num)
{
SharedPreferences.Editor editor;
editor = SP.edit();
editor.remove("key");
editor.putString("key", num);
editor.commit(); // IF commit() showing warning then use apply() instead .
editor.apply();
}
NOTE
If you don't care about the return value and you're using this from
your application's main thread, consider using apply() instead.
If you want to fetch by default 1 value when you when you don't save data in sharepreferance then you have to change in in your method like
public int getInt(String key) {
return SP.getInt(key, 1);
}
It will work for you.
You have to first save value in shared preferences so that you can retrieve it later. To save it use the below code
store.putInt(your int value);
and retrieve it from shared preference same like you are doing
int theme= store.getInt("theme");
You can do it this way :
private void saveTheme()
{
SharedPreferences sharedpreferences = getSharedPreferences("filename here", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putInt("theme", 1);
editor.commit();
}
private int getTheme()
{
SharedPreferences sharedpreferences = getSharedPreferences("filename here", Context.MODE_PRIVATE);
sharedpreferences.getInt("theme",0);
}
You can add them in Utility class or make a seperate PreferenceHelper class and make sharedPreference global.
Hope it Helps !!

Save variable in SharedPreferences based on which button is clicked

Im trying to make an EULA for my app, but there is a different EULA for the different countries we work with.
my idea was that i save a String in SharedPreferences like ZA for South Africa and KE for Kenya. So if you click the South Africa button, it will save the string in SharedPreferences as ZA and the same for Kenya. Once the button has been clicked it the new activity will then load the appropriate EULA by pulling the ZA or KE string from the SharedPreferences. This is what i have at the moment:
Country_select.java
public class country_select extends Activity {
private static final String TAG = "Logs";
public static final String PREFS_NAME = "PrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country_select);
final Button za_button = (Button) findViewById(R.id.btn_za);
Button ke_button = (Button) findViewById(R.id.btn_ke);
Log.i(TAG, "created buttons");
za_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Country_Selected", "ZA");
editor.commit();
}
});
Log.i(TAG, "set button settings for ZA");
ke_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Country_Selected", "KE");
editor.commit();
}
});
Log.i(TAG, "set button settings for KE");
}
I may have this totally incorrect but on the layout file there are 2 buttons, one for KE and one for ZA.
I would like it, when the new activity is loaded to read SharedPreferences whether it has ZA or KE? Is what i have done here correct?
Thank you
I think you're better off with using IntentExtras, in your first activity upon clicking the country button store the value inside a variable and when you want to start the new activity pass the data as an intent extra:
Intent intent= new Intent(getActivity(), NewActivity.class);
intent.putExtra("country", countryCode);
startActivity(intent);
And then inside the new activity you can retrieve the value like this:
String countryCode = getIntent().getExtras().getString("country");
In order to maintain Shared preference across the application i use it this way
, take a look
I saved a AppPrefes class as a seprate class in the package
public class AppPrefes {
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public AppPrefes(Context context, String Preferncename) {
this.appSharedPrefs = context.getSharedPreferences(Preferncename,
Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
/****
*
* getdata() get the value from the preference
*
* */
public String getData(String key) {
return appSharedPrefs.getString(key, "");
}
public Integer getIntData(String key) {
return appSharedPrefs.getInt(key, 0);
}
/****
*
* SaveData() save the value to the preference
*
* */
public void SaveData(String Tag, String text) {
prefsEditor.putString(Tag, text);
prefsEditor.commit();
}
public void SaveIntData(String key, int value) {
prefsEditor.putInt(key, value);
prefsEditor.commit();
}
/**
* delete all AppPreference
*/
public void deleteAll() {
this.prefsEditor = appSharedPrefs.edit();
this.prefsEditor.clear();
this.prefsEditor.commit();
}
In your Activity or Fragment were you would like to get or save data just use it like this
Decalre an object for the AppPrefes class
AppPrefes appPref;
Initialize in onCreate
appPref = new AppPrefes(getActivity(), "type name of your preference");
To save data to the preference use
appPref.SaveData("tag_name", "value to be saved);
To get data from the preference
appPref.getData("tag_name");
You can also save Integer values and clear all preference values if necessary just call the apporopriate methods.
Yes, the storing part is correct. Now you will need to access the stored value in your new activity.
Example-
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String storedCountry = sharedpreferences.getString("Country_Selected"); // could be null value if there is no value stored with Country_Selected tag.

Highscore still not saving to Shared Preferences [duplicate]

This question already has answers here:
Shared Preferences not saving when I compile my code
(3 answers)
Closed 8 years ago.
I am trying to save a simple Highscore to my game, but the data isn't saving to shared preferences.
SharedPrefManager.java:
package com.divergent.thumbler;
import android.content.Context;
import android.content.SharedPreferences;
// all methods are static , so we can call from any where in the code
//all member variables are private, so that we can save load with our own fun only
public class SharedPrefManager {
//this is your shared preference file name, in which we will save data
public static final String MY_EMP_PREFS = "MySharedPref";
//saving the context, so that we can call all
//shared pref methods from non activity classes.
//because getSharedPreferences required the context.
//but in activity class we can call without this context
private static Context mContext;
// will get user input in below variables, then will store in to shared pref
private static int HighScore;
public static void Init(Context context)
{
mContext = context;
}
public static void LoadFromPref()
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
// Note here the 2nd parameter 0 is the default parameter for private access,
//Operating mode. Use 0 or MODE_PRIVATE for the default operation,
settings.getInt("HighScore", HighScore);
}
public static void StoreToPref()
{
// get the existing preference file
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.putInt("HighScore", HighScore);
//final step to commit (save)the changes in to the shared pref
editor.commit();
}
public static void DeleteSingleEntryFromPref(String keyName)
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.remove(keyName);
editor.commit();
}
public static void DeleteAllEntriesFromPref()
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
}
public static void SetHighScore(int score)
{
HighScore = score;
}
public static int getHighScore()
{
return HighScore ;
}
}
I am saving my highscore with the following function:
public void highscoreSaver() {
SharedPrefManager.LoadFromPref();
if(finalScore > SharedPrefManager.getHighScore()) {
SharedPrefManager.SetHighScore(finalScore);
SharedPrefManager.StoreToPref();
}
}
And getting my highscore like this:
HighScore = SharedPrefManager.getHighScore();
Is there anything that im doing wrong? Please let me know
I think the problem lies in settings.getInt("HighScore", HighScore);
As per documentation here, SharedPreferences.getInt(String, int) returns an integer, the second parameter is for giving default value if there is no preference with the given key so you should do something like HighScore = settings.getInt("HighScore", 0); instead

SharedPreferences doesn´t retrieve Int value in different Activity

In my app I am storing integer and string data from different Fragments.
This data is succesfully retrieved in the same Fragment.
The String data is succesfully retrieved over the whole application.
The Integer data however cannot be retrieved from different activities. In the same Fragment however it can be. If i try to get an integer from a different activity, it´s always giving me my set default value.
Here is my code. Note that i´m already using constants to retrieve data.
to save numbers:
public void saveNumberChange(String s, int data){
String help = "com.example.test2.PREFERENCE_FILE_KEY_"+username;
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(help, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(s, data);
editor.commit();
}
and get them back out:
public int getNumber(String s){
int data;
String help = "com.example.test2.PREFERENCE_FILE_KEY_"+username;
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(help, Context.MODE_PRIVATE);
data = sharedPref.getInt(s, 0);
return data;
}
The funny thing is, when i´m storing the integer as strings, they can again be retrieved in the same activity, not though from another activity. With pure strings everything is fine.
Some more code:
Save integer:
saveNumberChange(BeyouApplicationClass.AGE, valueage);
Get integer:
getNumber(BeyouApplicationClass.AGE);
Thanks for your help. I hope you can help me.
You cant access it from another activity because you are only saving it on that activity using the context of that activity.
solution:
instead of using the context.getSharedPreferences of the activity use the PreferenceManager.getDefaultSharedPreferences for your whole application to share data among its activity
example:
saveNumberChange
public void saveNumberChange(String s, int data){
Context context = getActivity();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(s, data);
editor.commit();
}
getNumber
public int getNumber(String s){
int data;
Context context = getActivity();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
data = sharedPref.getInt(s, 0);
return data;
}
Try getting your preferences this way:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
in all activities, and getting the editor the same way
So what i found out is following.
For everybody that has the same problem:
Saving shared preferences from inside a fragment will lead to the problem i described earlier.
Only that specific fragment will be able to get the information back out.
So always save from fragment by calling its host activity.
What i did is this:
public static void saveNumberChange(String s, int data){
String help = "com.example.test2.PREFERENCE_FILE_KEY_"+username;
SharedPreferences sharedPref = context.getSharedPreferences(help, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(s, data);
editor.commit();
}
public static int getNumber(String s){
int data;
String help = "com.example.test2.PREFERENCE_FILE_KEY_"+username;
SharedPreferences sharedPref = context.getSharedPreferences(help, Context.MODE_PRIVATE);
data = sharedPref.getInt(s, 0);
return data;
}
make your method static so it can be called from within the attached fragment and everything works fine.

Save an int count and retrieve it to other activity

I am creating a game in which the user is given hints for every question, when the user presses the hints button, then the hint count has to reduce by 1, I am having lots of activities which will have same type of logic. how to edit data and get it where ever we want. Please help me out
You could just keep count value in a static variable inside your Application class.
In your AndroidManifest.xml you define.-
<application
android:allowBackup="true"
android:name=".YourApplicatinClass"
...
Then define YourApplicationApplication class like.-
public class YourApplicationClass extends Application {
public static int cont = 0;
}
And access cont value whenever you need with
YourApplicationClass.cont
You should just save it in SharedPreferences.
Have a look at this Question, that should give you the hint how to work with it.
You can write a static method to read an decrement the value saved in there
class Activity1{
onClickListener(){
GlobalSettings.getHits(context)
}
}
class Activity2{
onClickListener(){
GlobalSettings.getHits(context)
}
}
class GlobalSettings{
private static String PREFS_NAME = "myprefs";
private static String PREF_HITS = "hits";
private static int START_VALUE = 10;
public static int getHits(Context context){
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
return settings.getInt(PREF_HITS, START_VALUE);
}
public static void incrementHits(Context context){
SharedPreferences settings = getSharedPreferences(PREFS_NAME , 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(PREF_HITS, getHits(context) + 1);
editor.commit();
}
public static void decrementHits(Context context){
SharedPreferences settings = getSharedPreferences(PREFS_NAME , 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(PREF_HITS, getHits(context) - 1);
editor.commit();
}
}

Categories