Getting java.lang.nullPointerException using SharedPreferences - java

I am trying to save the date of file parsing, so that when next time user, opens the application, the date can be checked against the last parsing date.
I am using shared preference to save the data and retrieve it, but getting error. Here is the code :
SharedPreferences settings = getPreferences(0);
String today = new Date(System.currentTimeMillis()).toString();
SharedPreferences.Editor edit = settings.edit();
System.out.println("******** Today : " + today);
edit.putString("lastdate", today);
String fetch = settings.getString("lastdate", "0");
System.out.println("******** Fetch : " + fetch);
txtTest.setText(fetch);
But I am getting null pointer error, am I missing something?

Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.
Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences.
(1) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
(2) The recommended way is to use by the default mode, without specifying the file name
SharedPreferences preferences = PreferencesManager.getDefaultSharedPreferences(context);
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor object has to be used. Editor is the nested interface of the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also support methods like remove() and clear() to delete the preference value from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.

You need to change how you get the object
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);

Related

Android:How to save perennialy a variable?

I have a variable and I want to change it only the first time that I start my app. For example:
I open the app: Variable is not initialized. Variable changes to 4.
I close the app
I open the app Variable is 4.
And so on.
How can I do this?
I guess you are new to Android. You can save the values using "SharedPreferences".
Check this link : https://developer.android.com/training/basics/data-storage/shared-preferences.html
Also check out this example :
https://www.tutorialspoint.com/android/android_shared_preferences.htm
You can use this code :
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();
Here, MyPREFERENCES is the file name. Replace the "value" with the variable name.
Again, if you want to retrieve the value, then use:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.getBoolean("key", true);
//There are other methods like getInt(),getDouoble().getString() depending on the type of value
You can also write to a local file and use SQLite for that purposes if you would like to persist big object's data.

SharedPreferences is not updating its value

Below is a snippet of code that i use in my save settings function (DialogFragment):
String orderBy = mOrderBySpinner.getSelectedItem().toString();
String search = mSearchEditText.getText().toString().trim();
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(InventoryPreferences.ORDER_BY, orderBy);
editor.putString(InventoryPreferences.SEARCH_TERM, search);
editor.apply();
I then retrieve that data with the following (Activity):
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String orderBy = sharedPrefs.getString(InventoryPreferences.ORDER_BY, "name ASC");
String searchTerm = sharedPrefs.getString(
InventoryPreferences.SEARCH_TERM,"").trim();
These are my keys:
public static final String ORDER_BY = "orderBy";
public static final String SEARCH_TERM = "search";
Is there any reason as to why it wouldn't update the values when the key is the same?
getActivity().getPreferences(Context.MODE_PRIVATE);
is not
PreferenceManager.getDefaultSharedPreferences(this);
Use the second line in both methods.
From the docs:
https://developer.android.com/reference/android/app/Activity.html#getPreferences(int)
Retrieve a SharedPreferences object for accessing preferences that are
private to this activity
You are using two different methods to get access to a SharedPreferences file.
The first time using getActivity().getPreferences(Context.MODE_PRIVATE) you are calling Activity's getPreferences(int mode) which returns a SharedPreferences object which is supposed to be private to the activity which requests it. The name of the preferences file this SharedPreferences object points to is CLASS_NAME.xml
The second time using PreferenceManager.getDefaultSharedPreferences(this)
returns a SharedPreferences object which is supposed to be available and useful for the entire application. The name of the preferences file this SharedPreferences object points to is PACKAGE_NAME_preferences.xml.
So your problem is that you are using one file to write the preferences to and another to read them. Try using the more global thinking PreferenceManager.getDefaultSharedPreferences(Context context) to store preferences that relate to the entire application, and only use Activity.getPreferences(int mode) for preferences that only relate to a specific activity. (And then also remember to use the appropriate methods to retrieve them)
Use PreferenceManager to access SharedPreference.
Your code for updating preference value is correct.
Consider verifying that the values in input controls really changed
and verify, that the application has permission to write preferences.

Access SharedPreference and Editor object in other Java classes

In MainActivity.java I write
SharedPreferences pref = getApplicationContext().getSharedPreferences("My_Pref" , 0);
Then I create object of Editor to put data in it
Editor edit = pref.edit();
Then I put data
edit.putString("1","Hello");
edit.commit(); / edit.apply();
In Second.java, I get preferences:
SharedPreferences pref = getPreferences(0);
then I try to receive data like
pref.getString("1",null);
and set it to text of textview. But this does not work.
Also, how do I access Preferences and editor in other java classes properly? I cannot understand the concept.
You are writing to and reading from different preference files. Use the same file and it should work.
To get an instance of SharedPreferences you do this:
1) In activity MainActivity:
SharedPreferences pref =
getApplicationContext().getSharedPreferences("My_Pref" , 0);
2) In activitySecond:
SharedPreferences pref =
getPreferences(0);
The first form opens preference file "My_Pref", the second form opens a file named after your activity class, i.e.: "Second". So they are reading and writing in different files.
I always use this form to open a preferences file:
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(this);
Try this way
public void saveToSharedPrefrence(Context context, String word) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPreferences.edit();
if (sharedPreferences.contains("history")) {
preExistRemove(word, context);
} else {
editor.putString("history", word.trim());
editor.commit();
}
}
Check this for more details
Get the context of your activity
Context shrdContext= ActivityClass.getContextOfApplication();
Now pass the context to get your shared preferences in your another class
SharedPreferences myPrefs= PreferenceManager.getDefaultSharedPreferences(shrdContext);
You have 3 ways to access preferences for a Android application.
The first you used is
SharedPreferences pref = getApplicationContext().getSharedPreferences("My_Pref" , 0); is the first one. With this you can read and write to a custom-named shared preference file. In your case the name of your file would be My_Pref.
This one is useful if you want to have differents preferences differents domain as it allow you to create many shared preferences with differents names. (ex : preferences for timezone, preference for your user).
The second getPreferences(int) allow to access preferences for an Activity and is bind closely to the activity calling it. The file created is named using the Activity name. In your case Second.
The third method PreferenceManager.getDefaultSharedPreferences(Context) create a shared preference file like the first method, but this time the file is named using your application package name. This is the best methods to use shared preferences, if you intend to have only one shared preference file.
In your initial question you wrote a data in one file and tried to read in an other file, which result in an error. That's why like Rob Meeuwisse write you must use PreferenceManager.getDefaultSharedPreferences(Context)

How to retrieve data stored with Shared Preference in MainActivity class to SplashScreen activity class? [duplicate]

How do I retrieve shared preferences that have been saved from a
previous activity?
Do I need to enable file writing or some other manifest modifications?
You don't need any special manifest modificaiton to achieve that.
Assuming you have already saved preferences you can read those preferences at anytime doing something like I show bellow.
Write on Shared Preferences file:
SharedPreferences prefs = getSharedPreferences("your_file_name", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("yourStringName", "this_is_the_saved_value");
editor.commit(); // This line is IMPORTANT. If you miss this one its not gonna work!
Read from Shared Preferences file:
SharedPreferences prefs = getSharedPreferences("your_file_name",
MODE_PRIVATE); String string = prefs.getString("yourStringName",
"default_value_here_if_string_is_missing");
You can use a default file to save/ read your preferences. Just replace the first line of the two code snippets above by something like: SharedPreferences prefs = getDefaultSharedPreferences(getApplicationContext());
Thats it! Check the Android Developers dedicated page to this matter, here.
Hope it was usefull. Let me know about it.
You don't need to do anything special, other than make sure both activities are writing to/reading from the same file. Under the hood, preferences are just stored as an XML file.
So, your choices are:
1) Use PreferenceManager.getDefaultSharedPreferences() from both activities to write to the default file.
2) Use Context.getSharedPreferences() specifying a custom file name, and use the same name from both activities.
Shared Preferences are just that, shared. As long as you properly save the preferences after editting them by calling Editor.commit(), they will be available in the future.

Android save details screen

I am working on a small project that requires a details screen where the user inputs his details and they are permanently stored. The user must have the option to change the details as well if he needs to do so. I looked into the saved preferences library however it does not seem to offer such functionality.
To give a visual idea of what is required, something like this screen should be fine:
http://www.google.com.mt/imgres?start=97&num=10&hl=en&tbo=d&biw=1366&bih=643&tbm=isch&tbnid=aQSZz782gIfOeM:&imgrefurl=http://andrejusb.blogspot.com/2011/10/iphone-web-application-development-with.html&docid=YpPF3-T8zLGOAM&imgurl=http://2.bp.blogspot.com/-YRISJXXajD0/Tq2KTpcqWiI/AAAAAAAAFiE/-aJen8IuVRM/s1600/7.png&w=365&h=712&ei=rbX6ULTDCOfV4gTroIDoCg&zoom=1&iact=hc&vpx=834&vpy=218&dur=2075&hovh=314&hovw=161&tx=80&ty=216&sig=108811856681773622351&page=4&tbnh=155&tbnw=79&ndsp=35&ved=1t:429,r:4,s:100,i:16
Any help is much appreciated. Thanks in advance
You could easily use Shared Preferences to store user's details. Everytime the Preference screen is opened the stored data can then be extracted from the Shared Preferences and presented to the user for edit. ONce the edit is done the new data can be updated back in the the Shared Preferences.
Also look at this thread to see how this can be done.
Using SharedPreferences would be perfect for this kind of small amount of data which you want to store persistently.
// 'this' is simply your Application Context, so you can access this nearly anywhere
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To obtain from the preferences:
// You can equally use KEY_LAST_NAME to get the last name, etc. They are just key/value pairs
// Note that the 2nd arg is simply the default value if there is no key/value mapping
String firstName = prefs.getString(KEY_FIRST_NAME_CONSTANT, "");
Or to save:
Editor editor = prefs.edit();
// firstName being the text they entered in the EditText
editor.putString(KEY_FIRST_NAME_CONSTANT, firstName);
editor.commit();
You can achieve such functionality using SharedPreferences Class in android.
public void onCreate(Bundle object){
super.onCreate(object);
// Initialize UI and link xml data to java view objects
......
SharedPreferences myPref = getPreferences(MODE_PRIVATE);
nameView.setText(myPref.getString("USER_NAME", null));
passView.setText(myPref.getString("PASSWORD", null));
}
public void onStop(){
super.onStop();
if (isFinishing()) {
getPreferences(MODE_PRIVATE).edit()
.putString("USER_NAME", nameView.getText().toString())
.putString("PASSWORD", passView.getText().toString())
.commit()
}
}

Categories