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 !!
Related
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".
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
I am making a Highscore script for my game using Shared Preferences. I want this data to be only held for the phone it is installed on obviously. I have done the following, and the highscore shows and updates, but when I close out of the app and re open it, it resets.
if(finalScore > SharedPrefManager.getHighScore())
SharedPrefManager.SetHighScore(finalScore);
SharedPrefManager.StoreToPref();
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 = 0;
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,
HighScore = 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); // Age is the key and mAge is holding the value
//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 ;
}
}
Better don't store sensitive information in sharedpreference. All the users that have root permission can see and easily edit your sharedpreference(If it is not encrypted). So dont forget to encrypt all data.
Here is the chunk of code you need to store in sharedpreference
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("finalScore", yourscore);
editor.commit();
UPDATE
You are setting as
editor.putInt("HighScore", HighScore);
and getting as
HighScore = settings.getInt("Age",0);
You should use the same tag
UPDATE
Change
HighScore = settings.getInt("HighScore", HighScore);
to
settings.getInt("HighScore", HighScore);
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();
}
}
I want to save a flag for recognizing that my app is run for the first time or not. For this simple job I don't want to create database..
Is there a simple option to do this? I want to save and read little pieces of information only.
Use sharedPreference or files to save the data but better option is sharedPreference.
For Retrieving
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
For Saving
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", true);
editor.commit();
Use SharedPreferences.
SharedPreferences preferences = getSharedPreferences("prefName", MODE_PRIVATE);
SharedPreferences.Editor edit= preferences.edit();
edit.putBoolean("isFirstRun", false);
edit.commit();
A proper way to do this is by using the Android class SharedPreferences which is used for things like this.
Storing Settings
SharedPreferences settings = getSharedPreferences(NAME_OF_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("appPreviouslyStarted", true);
editor.apply();
Don't forget to apply or your mutations to the settings won't be saved!
You can create multiple settings by using different NAME_OF_PREFERENCES. The settings are stored on the device so will be available after closing the application.
When you try to retrieve NAME_OF_PREFERENCES that is not already created, you create a new one. See more behavior like this here.
apply() versus commit()
You can use editor.apply() as well as editor.commit(), the only difference is that apply() does not return a boolean value with if the edit was successful or not. editor.apply() is therefor faster and more commonly used.
What is MODE_PRIVATE
You can see all about the different modes here. For your case MODE_PRIVATE is fine.
Retrieving settings
SharedPreferences settings = getSharedPreferences(NAME_OF_PREFERENCES, MODE_PRIVATE);
boolean silent = settings.getBoolean("silentMode", false);
When retrieving a settings from a SharedPreferences object you always have to specify a default value which will be returned when the setting was not found. In this case that's false.
I suggest you to go for SharedPreference persistent storage. Its very easy and fast storing/retrival for small amount of information.
See the code to get the value from SharedPreference
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
and to Store value in SharedPreference
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
You can do one class for example:
(like a object for instance)
import android.content.Context;
import android.content.SharedPreferences;
public class SettingsMain {
Context context;
SharedPreferences preferences;
SharedPreferences.Editor editor;
private static final String PREFER_NAME = "settingsMain";
public static final String KEY_VIBRATE = "switchVibrate";
public SettingsMain(Context context) {
this.context = context;
setPreferences();
}
private void setPreferences(){
preferences = context.getSharedPreferences(PREFER_NAME, context.MODE_PRIVATE);
editor = preferences.edit();
}
public void cleanPreferences(){
editor.clear();
editor.commit();
}
public void setStatusVibrate(Boolean status){
editor.putBoolean(KEY_VIBRATE, status);
editor.commit();
}
public Boolean getstatusVibrate(){
return preferences.getBoolean(KEY_VIBRATE, true);
}
}
On your activity call:
public class Home extends AppCompatActivity {
private SettingsMain settings;
private SwitchCompat switchVibrate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.master);
setResources();
getSettings();
}
private void setResources(){
switchVibrate = (SwitchCompat) findViewById(R.id.master_main_body_vibrate_switch);
switchVibrate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
settings.setStatusVibrate(isChecked);
}
});
}
private void getSettings(){
settings = new SettingsMain(this);
switchVibrate.setChecked(settings.getstatusVibrate());
}
}
What about using static variables globally?
You can do this as given in this tutorial. I know handling Content providers are unnecessary just to keep some flags.
Else you can check out Shared Preferences provided by Android. Here's a good example to get started.
This would be my recommendation.