Making a variable value constant in android studio - android

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

Related

Multiple SharedPreferences are not being stored

I am working with SharedPrefrences. I have multiple shared preferences in pref. I am changing values 0 to n-1 in a loop while, other value is User Score. Maybe there is some problem with my using of commit(), but the value is not updated. Can you suggest what should I do?
SharedPreferences pref = getApplicationContext().getSharedPreferences("Scorepref", 0);
SharedPreferences.Editor editor = pref.edit();
for (int i = 0; i < mQuestionBank.length; i++) {
editor.putBoolean(Integer.toString(i), false);
editor.commit();
}
mAnswered.setText( "0/" +Integer.toString(mQuestionBank.length));
mScoreval = 0;
mAnswered_count=0;
editor.putInt("User_score", 0);
editor.commit();
mScore.setText("0");
You didn't show us the code how you're trying read the data from prefs but anyway in your case, if you're not able to read the data by prefs.getBoolean then you can iterate over pref.getAll() like:
if (pref.getAll() != null) {
for (int i = 0; i < mQuestionBank.size(); i++) {
if (pref.getAll().get(String.valueOf(i)) instanceof Boolean) {
final Boolean yourSavedBoolean = (Boolean) pref.getAll().get(i);
}
}
}
Or if you need only one value then:
if (pref.getAll() != null) {
Boolean yourSavedBoolean = false;
if (pref.getAll().get("0") != null && pref.getAll().get("0") instanceof Boolean) {
yourSavedBoolean = (Boolean) pref.getAll().get("0");
}
}

SharedPreferences not updated on change, only with app reset?

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

Android Material Dialog and Store Selected Value

My application is related to alarm. I used material AlertDialog in my application. I choose one value from AlertDialog and press choose button. I want to store that selected values. It value sets until I do not changed it. How do I?
final Dialog dialog = new MaterialDialog.Builder(Settings_Activity.this)
.title(R.string.full_battery_alarm1)
.iconRes(R.mipmap.ic_launcher)
.limitIconToDefaultSize()
.items(R.array.full_battery_alarm)
.itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {
#Override
public boolean onSelection(MaterialDialog mdialog, View view, int pos, CharSequence text) {
manager.sessionWork(pos);
showToast(pos + " = " + text);
int i = Integer.parseInt(text.toString());
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Settings_Activity.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("select full", Integer.toString(i));
editor.apply();
String abc = preferences.getString("select full", null);
final int l = Integer.parseInt(abc);
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
showToast("level full" + level);
if (level == l) {
showToast("level full 2"+level);
Intent i1 = new Intent(Settings_Activity.this, StopActivity.class);
i1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i1);
finish();
}
}
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
mdialog.setSelectedIndex(pos);
return true;
}
})
.positiveText(R.string.choose)
.show();
Store it in shared preference or just use a db line sql lite
You can use SharedPreferences like this. Create your SharedPreferences and Editor.
static SharedPreferences sharedData;
static SharedPreferences.Editor editor;
now
sharedData = getSharedPreferences("mySharedPreference", Context.MODE_PRIVATE);
editor = sharedData.edit();
after this to save your value do
editor.putString("valueKey", ""+yourvaluevariable); editor.commit();
Now this value is saved and will be retrieved event when you will start the app later after closing it.
To access that value afterwards use
sharedData.getString("valueKey", "");

reading preferences as int throws exception

I'm trying to read the value stored in preferences as Int, its throwing me classcast exception. Here is the code
SharedPreferences prefs = ct.getSharedPreferences("volumepreference", 0);
SharedPreferences.Editor editor = prefs.edit();
int Past_phone_audio_mode = -1;
try
{
Past_phone_audio_mode = prefs.getInt("volumestate", -1);
}
catch(Exception ee)
{
}
May i know whats wrong in my code
To save a preference int value:
final SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// Get preference in editor mode
final SharedPreferences.Editor editor = prefs.edit();
// Set the Integer value
editor.putInt("volumestate", 1);
// Finally, save changes
editor.apply();

How to save and fetch integer value in Shared Preference in android?

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

Categories

Resources