Android SharedPreferences , how to save a simple int variable
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", yourIntValue);
editor.commit();
the you can get it as:
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", -1);
The SharedPreference
interface gives you access to the an xml file, and a easy way to modify it through its editor. The file is stored in /data/data/com.your.package/shared_prefs/
and you can access it onlu through this SharedPreference
API
How Save a int variable with SharedPreferences?
SharedPreferences prefs = getSharedPreferences(MUTATIO, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt("semper", R.drawable.lux );
editor.putInt("semper2", 1);
editor.commit();
Storing an int value using Shared preferences
Your way of doing it is wrong
1.> Use Mode_PRIVATE(Used when you want your shared preference file should be accessible only to your app) instead of MODE_WORLD_WRITABLE(Used when you want your shared preference file should be accessible only outside your app)
2.> Make a method to save the state of flag
public void saveFlag(){
pref=getSharedPreferences("Sai",Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putInt("lang_us", flag);
editor.commit();
}
3.> Call this method whenever you change flag
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.flag0:
flag=0;
saveFlag();
System.err.println("Flag : " + flag);
break;
case R.id.flag1:
flag=1;
saveFlag();
System.err.println("Flag : " + flag);
break;
default:
break;
}
4.> Then in your onCreate() method you should retrieve this value.
pref=getSharedPreferences("Sai",Context.MODE_PRIVATE);
flag = prefs.getInt("lang_us", 0);
SharedPreferences Save value of Int in a TextView
I explained where I made changes
public class MainActivity extends Activity {
Button search;
TextView tvRing;
//Making sharedpreferences and integers global for ease of use
private SharedPreferences prefs;
private int redRing, someint;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (Button) findViewById(R.id.radar);
tvRing = (TextView) findViewById(R.id.ring);
//Someint default value is 0 if not ever saved before
prefs = getSharedPreferences("sharedPreferences", Context.MODE_PRIVATE);
someint = prefs.getInt("someint", 0);
tvRing.setText("Objects found : " + String.valueOf(someint));
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Load the lates someint in onclick
someint = prefs.getInt("someint", 0);
//redring is the dummy integer to increment someint
redRing=someint+1;
//Save the incremented value
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("someint", redRing);
editor.commit();
//To show the latest number on the tv
lastNumber();
}
});
}
public void lastNumber() {
prefs = getSharedPreferences("sharedPreferences", Context.MODE_PRIVATE);
someint = prefs.getInt("someint", 0);
tvRing.setText("Objects found : " + String.valueOf(someint));
}
}
Why cannot save INT to SharedPreferences?
I'd check what's the value of the Number and Profile variables you declared... you are using their values as keys, so if they have conflicting names, you might be overwriting one setting with the other even though the code looks right.
I'd recommend replacing this:
private String Number;
private String Profile;
With this:
private final String NUMBER = "Number";
private final String PROFILE = "Profile";
And then using those constants when setting/getting your preference value.
Android SharedPreferences , issue with saving simple int variable
Your AllRequestsCount
variable used at countClick
function is null.
Just use i++;
than i = countClick();
How to use SharedPreferences in Android to store, fetch and edit values
To obtain shared preferences, use the following method
In your activity:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
To edit and save preferences
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:
<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
Edit==>
I noticed, it is important to write difference between commit()
and apply()
here as well.
commit()
return true
if value saved successfully otherwise false
. It save values to SharedPreferences synchronously.
apply()
was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronous commit.
More detail is here.
Saving a variable using SharedPreferences
first of all, create an AppPreference class and create some getter and setter in your class like this :-
public class AppPrefrences {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static String getUserName(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getString("userName", "");
}
public static void setUserName(Context ctx, String value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putString("userName", value);
mPrefsEditor.commit();
}
public static void clearAllPreferences(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.clear();
mPrefsEditor.commit();
}
}
this is my code change code according to your need and set your values in methods in after that for getting value just call the get methods
Related Topics
Write File to Location Other Than Sdcard Using Android Ndk
Android Studio 3.0 Compile Issue (Cannot Choose Between Configurations)
Passing JSONobject into Another Activity
Custom 'Keyboard' Built in an Application on Android
Dependency Ignored Because of Conflict Android Studio
Add Dynamic Text Over Android Seekbar Thumb
Kitkat Kills: Not Allowed to Load Local Resource: File:///Android_Asset/Webkit/Android-Weberror.Png
Given a Tensor Flow Model Graph, How to Find the Input Node and Output Node Names
How to Hide the Share Action (Which Use Most) Icon Near the Share Action Provider
How to Get the File *.Apk Location in Android Device
Android - How to Intercept the 'Install Application' Intent
Custom Fonts in Android Phonegap
Do Gcm Registration Id's Expire
Difference Between Android: and App: Prefix in Android Xml
How to Fix "Fail to Connect to Camera Service" Exception in Android Emulator