I am developing an app that displays a rule in relation to card being drawn. The user can set custom rules in the SettingsActivity and this is loaded into the GameActivity.
This works no problem, however, if the user decides to change their rules, or reset to default, the only way for this to update in the GameActivity is to fully quit the App and restart. I have tried using reCreate(), but it didn't work. and when I used finish(), it just quit the app completely.
In the GameActivity, I also tried putting my call to the loadRules method in the onResume() method, but it did nothing.
Code snipped from SettingsActivity:
public void setDefault(View v){
ruleAce = rules[0];
ruleTwo = rules[1];
ruleThree = rules[2];
ruleFour = rules[3];
ruleFive = rules[4];
ruleSix = rules[5];
ruleSeven = rules[6];
ruleEight = rules[7];
ruleNine = rules[8];
ruleTen = rules[9];
ruleJack = rules[10];
ruleQueen = rules[11];
ruleKing = rules[12];
saveRules();
}
private void saveRules(){
SharedPreferences ace, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king;
SharedPreferences.Editor editor;
ace = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
editor = ace.edit();
editor.putString(RULE_ACE, ruleAce);
editor.apply();
two = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
editor = two.edit();
editor.putString(RULE_TWO, ruleTwo);
editor.apply();
three = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
editor = three.edit();
editor.putString(RULE_THREE, ruleThree);
editor.apply();
four = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
editor = four.edit();
editor.putString(RULE_FOUR, ruleFour);
editor.apply();
five = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
editor = five.edit();
editor.putString(RULE_FIVE, ruleFive);
editor.apply();
six = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
editor = six.edit();
editor.putString(RULE_SIX, ruleSix);
editor.apply();
seven = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
editor = seven.edit();
editor.putString(RULE_SEVEN, ruleSeven);
editor.apply();
eight = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
editor = eight.edit();
editor.putString(RULE_EIGHT, ruleEight);
editor.apply();
nine = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
editor = nine.edit();
editor.putString(RULE_NINE, ruleNine);
editor.apply();
ten = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
editor = ten.edit();
editor.putString(RULE_TEN, ruleTen);
editor.apply();
jack = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
editor = jack.edit();
editor.putString(RULE_JACK, ruleJack);
editor.apply();
queen = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
editor = queen.edit();
editor.putString(RULE_QUEEN, ruleQueen);
editor.apply();
king = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
editor = king.edit();
editor.putString(RULE_KING, ruleKing);
editor.apply();
}
GameActivity snippet:
public class kingGame extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_king_game);
loadRules();
shuffleDeck();
}
#Override
protected void onResume(){
super.onResume();
setContentView(R.layout.activity_king_game);
loadRules();
}
//Sets the Rules
static String aceRule, twoRule, threeRule, fourRule, fiveRule, sixRule, sevenRule, eightRule, nineRule, tenRule, jackRule, queenRule, kingRule;
static String[] defaultrules = {DEFAULT RULES IN HERE}
public void loadRules(){
SharedPreferences settings;
settings = getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
aceRule = settings.getString(RULE_ACE, defaultrules[0]);
twoRule = settings.getString(RULE_TWO, defaultrules[1]);
threeRule = settings.getString(RULE_THREE, defaultrules[2]);
fourRule = settings.getString(RULE_FOUR, defaultrules[3]);
fiveRule = settings.getString(RULE_FIVE, defaultrules[4]);
sixRule = settings.getString(RULE_SIX, defaultrules[5]);
sevenRule = settings.getString(RULE_SEVEN, defaultrules[6]);
eightRule = settings.getString(RULE_EIGHT, defaultrules[7]);
nineRule = settings.getString(RULE_NINE, defaultrules[8]);
tenRule = settings.getString(RULE_TEN, defaultrules[9]);
jackRule = settings.getString(RULE_JACK, defaultrules[10]);
queenRule = settings.getString(RULE_QUEEN, defaultrules[11]);
kingRule = settings.getString(RULE_KING, defaultrules[12]);
}
/* Creates the Deck */
/* Shuffles the Deck */
public void shuffleDeck(){
cardsLeft = 52;
cardNum = 0;
for (int i = 0; i < RANK.length; i++){
for (int j=0; j < SUITS.length; j++){
deck[SUITS.length*i + j] = RANK[i] + " Of " + SUITS[j];
}
}
for (int i = 0; i < n; i++){
int r = i + (int) (Math.random() * (n-i));
String temp = deck[r];
deck[r] = deck[i];
deck[i] = temp;
}
}
/* Button Press Draws the Card */
public void drawCard(View view) {}
After that it is just the methods to printCard(), showRule(), and newGame().
newGame is only called when the game finishes (reaches the end of the deck).
showRule just displays the rules loaded into aceRule, twoRule, etc in response to which card is drawn.
printCard displays the drawn card.
So my question is, how do I force the GameActivity to check for changes in the SharedPreferences when the activity is resumed?
In the onPause method, you could save the values with .edit().putX().apply() on the shared prefs object
Related
I'm very new to coding in android, so I barely know any of the syntaxes. I am defining a variable in MainActivity.java and assigning it a random 4 digit value. I want to assign this value only once, when the app is installed/updated, and not every time the user opens the app. Help me out if any of you know a fix for this. The following is my current code
Random r = new Random();
int i1 = r.nextInt(9999 - 1) + 1;
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString("key for value", somrRandonNumber);
editor.putBoolean("is first lunch", false);
editor.commit();
Then retrive it with
int number = sharedPref.getInt("key for value";
Sometimes you need to specify a default value like:
SharedPref.getBoolean("is first lunch",true);
Good luck
Use SharedPreference for saving value use this code
int i1=0;
if (getIntValue() == 0) {
Random r = new Random();
i1 = r.nextInt(9999 - 1) + 1;
saveIntValue(i1);
} else {
i1 = getIntValue();
}
here are two method
public void saveIntValue(int myIntValue) {
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", myIntValue);
editor.commit();
}
public int getIntValue() {
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", 0);
if (myIntValue == 0) {
return 0;
} else {
return myIntValue;
}
}
Store in Preference if value is 0 else get stored value
Random r = new Random();
int value= r.nextInt(9999 - 1) + 1;
if(getValue()==0)
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putInt("uniqueInt", value).apply();
else {
int uniqueIntFromPref = getValue();
}
Retrieve from Preference
private int getValue() {
return PreferenceManager
.getDefaultSharedPreferences(context)
.getString("uniqueInt", 0);
}
Just copy and paste above code
String stored contains "1.0" in it. and I want to increase its value by 0.5, every time I press the button. But instead, my output becomes "1.00.5". How do I fix this?
String stored = userspeed.getText().toString();
String speedplus = stored + 0.5;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus.toString());
editor.apply();
UPDATE
public class ProgramActivity extends AppCompatActivity {
EditText userspeed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_program);
userspeed = (EditText) findViewById(R.id.userspeed);
//load values
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String stored = preferences.getString("user_speed", "1.0");//default
userspeed.setText(stored, TextView.BufferType.EDITABLE);
}
public void adduserspeed(View view) {
String stored = userspeed.getText().toString();
double storedValue = Double.parseDouble(stored);
String speedplus = String.valueOf(storedValue +0.5f);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus);
editor.apply();
}
}
First, you need to convert your string value to a float value, then perfom the add operation and finally convert the result to a string so you can store as a string in shared preferences.
final String stored = userspeed.getText().toString();
final float storedValue = Float.parseFloat(stored);
final String speedplus = String.valueOf(storedValue + 0.5f);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus);
editor.apply();
If you want to use a double value, simply replace first lines as the follows:
final String stored = "1.0";
final double storedValue = Double.parseDouble(stored);
final String speedplus = String.valueOf(storedValue + 0.5d);
UPDATE
Your problem is that within adduserspeed(View view) method your are not retrieving the stored value from preferences, your are retrieving from the EditText, and you are not updating that EditText value, so every time you execute adduserspeed(View view) method, the value you are storing on preferences is 1.0 + 0.5, because you EditText value is 1.0 until you re-open your app. When you re-open your app your EditText value is 1.5 and so on...
I have improved your code and now works well, anyway, do not just copy my code, try to understand it so you can learn.
public class MainActivity extends AppCompatActivity {
private EditText userSpeed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.userSpeed = (EditText) findViewById(R.id.userspeed);
setUserSpeedText();
}
public void adduserspeed(View view) {
final String stored = getUserSpeedValue();
final double storedValue = Double.parseDouble(stored);
final String speedPlus = String.valueOf(storedValue + 0.5f);
setUserSpeedValue(speedPlus);
setUserSpeedText();
}
private String getUserSpeedValue() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
return preferences.getString("user_speed", "1.0");
}
private void setUserSpeedValue(final String newSpeedValue) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", newSpeedValue);
editor.apply();
}
private void setUserSpeedText() {
if (null != this.userSpeed) {
this.userSpeed.setText(getUserSpeedValue());
}
}
}
You can also use double like:
String speedplus = (Double.parseDouble(stored)+0.5).toString();
Try parsing stored i.e. 1.0 as Double and then add 0.5d
String speedplus = String.valueOf((Double.parseDouble(stored) + 0.5d));
Final code
String stored = userspeed.getText().toString();
String speedplus = String.valueOf((Double.parseDouble(stored) + 0.5d));
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("user_speed", speedplus.toString());
editor.apply();
String stored = userspeed.getText().toString();
float speedplus = Float.parseFloat(stored) + 0.5;
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putFloat("user_speed", speedplus);
editor.apply();
Parse the string value to int and then do mathematical operation. Otherwise string concatenation will happen.
The quickest hack would be:
String speedplus = String.valueOf(Float.parseFloat(stored) + 0.5F);
However, your next question will no doubt be "Why is my result 1.499999999?", which is answered here in detail.
I want to save and fetch the static integer value of Snow Density in Shared Preferences and change when user select another value in the Single choice.
My Code :
public static int mSnowDensity;
AlertDialog.Builder mABuilder = new AlertDialog.Builder(AAA.this);
final CharSequence mCharSequence[] = { "Low", "Medium", "High" };
mABuilder.setTitle("Set Density of Snow");
mABuilder.setSingleChoiceItems(mCharSequence,
WallpaperServices.mDensitySnow,
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 2) {
mSnowDensity = 90;
/*I Want to save mSnowDensity Value In Shared Preferences */
} else if (which == 1) {
mSnowDensity = 60;
} else {
mSnowDensity = 30;
}
dialog.dismiss();
}
});
You can use shared preferences as follows
//To save
SharedPreferences settings = getSharedPreferences("YOUR_PREF_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("SNOW_DENSITY",mSnowDensity);
editor.commit();
//To retrieve
SharedPreferences settings = getSharedPreferences("YOUR_PREF_NAME", 0);
int snowDensity = settings.getInt("SNOW_DENSITY", 0); //0 is the default value
getSharedPreferences() is a method of the Context class. If you are inside a Activity or a Service (which extend Context) you can use it like in this snippet. Else you should get the context using getApplicationContext() and then call getSharedPreferences() method.
For more options you can refer to the documentation at http://developer.android.com/guide/topics/data/data-storage.html#pref
To save in the SharedPreferences:
private final String PREFS_NAME = "filename";
private final String KEY_DENSITY = "den";
Context ctx = getApplicationContext();
SharedPreferences sharedPreferences = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_DENSITY, mSnowDensity);
editor.commit();
To get the value:
Context ctx = getApplicationContext();
String strSavedValue = null;
SharedPreferences sharedPreferences = ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
strSavedValue = sharedPreferences.getInt("den", anyDefaultValue);
Save the value in prefrence
private void SavePreferences(String key, int value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
get the value from preference
private void showPreferences(String key){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
int savedPref = sharedPreferences.getInt(key, 0);
}
You can use the key as the shared preference name
Initialization
We need an editor to edit and save the changes in shared preferences. The following code can be used to get the shared preferences.
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 :- for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true);
editor.putString("key_name", "string value");
editor.putInt("key_name", "int value");
editor.putFloat("key_name", "float value");
editor.putLong("key_name", "long value");
editor.commit();
Retrieving Data
pref.getString("key_name", null); // getting String
pref.getInt("key_name", -1); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Clearing or Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
editor.clear();
editor.commit(); // commit changes
Saving preference is not a troubling task. But if you have a lot of such configurable options you could use a PreferenceActivity and override onSharedPreferenceChanged.
More details here http://developer.android.com/guide/topics/ui/settings.html
I'm building an app which searches the web using search engine. I have one edittext in my app from which user will search the web. I want to save the search keywords just like browser history does. I'm able to save and display it with the last keyword but I can't increase the number of searches result. I want to display the last 5 searhes. Here is my code :
public class MainActivity extends Activity implements OnClickListener {
Button insert;
EditText edt;
TextView txt1, txt2, txt3, txt4, txt5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.search_word);
txt1 = (TextView) findViewById(R.id.txt1);
txt1.setOnClickListener(this);
insert = (Button) findViewById(R.id.insert);
insert.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if ((edt.getText().toString().equals(""))) {
Toast.makeText(
getBaseContext(),
"Whoa! You haven't entered anything in the search box.",
Toast.LENGTH_SHORT).show();
} else {
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
String text = edt.getText().toString();
editor.putString("key", text);
editor.commit();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG)
.show();
}
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(this);
String text = app_preferences.getString("key", "null");
txt1.setText(text);
}
public void onClick(View v) {
String text = txt1.getText().toString();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_SHORT).show();
}
}
Please help me in overcoming this problem.
SAVE ARRAY
public boolean saveArray(String[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++)
editor.putString(arrayName + "_" + i, array[i]);
return editor.commit();
}
LOAD ARRAY
public String[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
String array[] = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(arrayName + "_" + i, null);
return array;
}
Convert your array or object to Json with Gson library and store your data as String in json format.
Save;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString(TAG, json);
editor.commit();
Read;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString(TAG, null);
Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
ArrayList<ArrayObject> arrayList = gson.fromJson(json, type);
Original answer: Storing Array List Object in SharedPreferences
So I'm trying to save the highest score with sharedPreferences but I am running into trouble. I don't know how I would set it up to only take the highest score and display it.
What I have now will only display the current score that the player recieves. Here is what I have so far that doesnt work:
public class GameOptions extends Activity {
int theScore;
TextView highScore;
public static String filename = "MyHighScore";
SharedPreferences spHighScore;
int dataReturned;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.in_game_menu);
TextView tvTheScore = (TextView) findViewById(R.id.textView2);
TextView highScore = (TextView) findViewById(R.id.high_score);
Bundle gotScore = getIntent().getExtras();
theScore = gotScore.getInt("scoreKey");
//String thisIsTheScoreToDisplay = theScore.toString();
tvTheScore.setText("SCORE: "+theScore);
spHighScore = getSharedPreferences(filename, 0);
SharedPreferences.Editor editor = spHighScore.edit();
editor.putInt("highScoreKey", theScore);
editor.commit();
int dataReturned = spHighScore.getInt("highScoreKey", 0);
highScore.setText("" + dataReturned);
by this you can save your score
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString(MY_SCORE_KEY, HIGHEST_SCORE);
prefsEditor.commit();
and get like this
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String highestScore = myPrefs.getString(MY_SCORE_KEY, "nothing");
I hope this will help you..
Just before Saving the high score, Fetch the current high score which is saved in the preferences and check whether it is less than the highscore or not. if it is less then save the new one in to Shared preferences or else just leave the past one as highest.