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();
}
}
Related
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 !!
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".
I am having issues loading the sharedpreferences. This is my first app with no prior coding experience. The app allows the user to count their number of "Drinks" and "Shots".
The buttons increase their appropriate textView by "1". When I close the app and open it the numbers stay intact and the buttons keep increasing the value by "1".
The problem is When the app is destroyed and opened. The textView's will show the numbers that were left, but when I press a button they rest back to 1. So, the the correct numbers are being loaded, but the buttons are resting those numbers.
I hope this is clear enough. Please, let me know if I need to explain it better. I'm usually able to figure out all my problems through a lot of internet searches. I just finally hit a wall.
private Button clearButton;
private Button drinkButton;
private Button shotButton;
private TextView textDrink;
private TextView textShot;
private int counterDrink = 0;
private int counterShot = 0;
public static final String DRINK_DATA = "DrinkData";
public static final String DEFAULT = "0";
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
loadSavedPreferences();
}
...
private void loadSavedPreferences(){
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
String dataDrinkReturned = prefs.getString("DrinkData", DEFAULT);
String dataShotReturned = prefs.getString("ShotData", DEFAULT);
textDrink.setText(dataDrinkReturned);
textShot.setText(dataShotReturned); }
'
#Override
protected void onPause(){
super.onPause();
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
String shotData = textShot.getText().toString();
String drinkData = textDrink.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("DrinkData", drinkData);
editor.putString("ShotData", shotData);
editor.commit();
}
`
You forget to initialize the int-counters:
private void loadSavedPreferences(){
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
String dataDrinkReturned = prefs.getString("DrinkData", DEFAULT);
String dataShotReturned = prefs.getString("ShotData", DEFAULT);
counterDrink = Integer.parseInt(dataDrinkReturned);
counterShot = Integer.parseInt(dataShotReturned );
textDrink.setText(dataDrinkReturned);
textShot.setText(dataShotReturned);
}
Although i feel it would be better than to save the int-values in the shared preferences instead of the string-values.
private void loadSavedPreferences(){
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
counterDrink = prefs.getInt("DrinkData", 0);
counterShot = prefs.getInt("ShotData", 0);
textDrink.setText(""+counterDrink);
textShot.setText(""+counterShot);
}
#Override
protected void onPause(){
super.onPause();
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
editor.putInt("DrinkData", counterDrink );
editor.putInt("ShotData", counterShot );
editor.commit();
}
That's because you're not setting the counter variables (counterDrink and counterShot) to the correct amount, and are always reset upon restarting the activity.
Instead of saving the counters to SharedPreferences as a String, I suggest saving it as an integer, and on top of setting the TextViews to the correct amount, you also need to set the counterDrink and counterShot.
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);