How to share 1 SharedPreferences file between 2 activities - android

I have got a SharedPreferences file in my Activity1.
void saveDays(){
Log.w(TAG, "Start saveDays");
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putInt("Days", days);
editor.commit();
}
Then I need to use days in my Activity2. So how can I load it?

In Activity2, where you want to get access to that preference:
int days = getPreferences(MODE_PRIVATE).getInt("Days", DEFAULT_DAY);
Where DEFAULT_DAY is the default value to use if there is no "Days" preference available.

You want to name the preferences and access them with that name in both
SharedPreferences prefs =
getSharedPreferences("myPrefs", MODE_PRIVATE);
And then its as simple as retrieving the int...
int days = prefs.getInt("Days", 1);

Related

Get last login details without webservicing

need an idea to get last login details(DATE OF LAST LOGIN) on login without webservicing concept
Store Last login date into SQLLITE database when you need last login detail fetch this values from SQLLITE database.
instead of sqlite use SharedPreferences
you will have to create an object of shared preference and an editor
it will be similiar to this:
SharedPreferences sp;
SharedPreferences.Editor ed;
ed=sp.edit();
ed.putBoolean("username",username);
ed.commit(); //**DONT FORGET TO COMMIT**
sp = getSharedPreferences("MenuData", MODE_PRIVATE);
if(!sp.contains(null))
{
username=sp.getBoolean("username",defaultvalue);// you need to add an default value
if(username.equals("admin")){
//do watever u like
}
}
soloved the problem,
setting the value before even putting;
min=c.get(Calendar.MINUTE);
seconds=c.get(Calendar.SECOND);
SharedPreferences prefs1 = getSharedPreferences(
"DATE", MODE_PRIVATE);
datee = prefs1.getString("SUBDATE", null);
DATE1.setText(datee);
SharedPreferences.Editor editor = getSharedPreferences("DATE", MODE_PRIVATE).edit();
editor.putString("SUBDATE", min+" "+seconds+" ");
editor.commit();

how to pass data to more number of activities

I would like to pass data from one activity to another.If it is two or three activities we can send data via intent.suppose more number of activities are present (approximately 20).how can i pass data from first activity to last activity?
i want to go Activity A-->B-->C-->D-->......Y-->Z
if we send data via intent(put Extra) that is worst method.
is there any other way to send data?
thanks in advance
I would use SharedPreferences for this.
This will be easier because, we can change it anywhere in any activity and access them as needed. And we don't need to pass on each and every activity transition.
Simple example:
To set value in shared preference
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Nabin");
editor.putInt("idName", 12);
editor.commit();
And retrieve as
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
You can refer here more about it.
If you need some data to multiple activities, Just save data into SharedPreference and you will be able to access to all activities.
Here is full tutorial.
Save Data
// Create object of SharedPreferences.
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
SharedPreferences.Editor editor= sharedPref.edit();
//put your value
editor.putString("name", strName);
editor.putString("pwd", strPass);
editor.commit(); //commits your edits
Retrieve Data
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
String name = sharedPref.getString("name", "");
String password = sharedPref.getString("pwd", "");
If it's not a must case to use activities, you can change activities to fragments, attach them to same activity, cache your data in activity and get it from fragments.

Android SharedPreferences , how to save a simple int variable [duplicate]

This question already has answers here:
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 9 years ago.
I am trying for the last hour to save an integer in my Android application. I read that this can be done using the SharedPreferences. However i dont understand why it seems so confusing to do so.
How can i simply save an int variable ? And then when i run the application again , how can i interact with this variable again?
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
public void SaveInt(String key, int value){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public void LoadInt(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
savedValue = sharedPreferences.getInt("key", 0);
}
If you want to save the variable somewhere, you have to write SaveInt("key", 5); With this you will save the value 5, while the first default value is 0. If you want to load it and use it in another activity, you have to write both of these methods there, and call LoadInt(); where you need the variable. The savedValue is a predefined integer (this needs to be declared everywhere you would like to use the saved variable)
This is the example of setting Boolean preferences. You can go with Integer also.
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
Hope this might be helpful.

How to make a persistent counter variable in an Android app?

I'm just starting out.
I'm trying to increment a simple counter, every time I run the project on the emulator.
I thought adding an integer type item in strings.xml would help, but that's final, and can't be modified.
Basically I'd just display in my app's first basic screen:
Started: N where N would be the Nth time I've launched the project from Eclipse.
How can I make such a counter that's persistent across application launches and exits?
Got it:
SharedPreferences pref = getPreferences(MODE_PRIVATE);
int tempN=pref.getInt("N", 0);
tempN++;
SharedPreferences.Editor editor = pref.edit();
editor.putInt("N",tempN);
editor.commit();
msgBox.setText("Started:"+tempN);
One thing I still don't understand, that when I call pref.getInt("N",0), is the key-value pair <N,0> automatically created?
You can use shared preference for that . You can store integer number in shared preference and get value of it when ever you want.
Try this.
SharedPreferences prefs = getSharedPreferences("Share", Context.MODE_PRIVATE );
Editor editor = prefs.edit();
editor.putInt("Value", 1 );
editor.commit();
for get value
prefs.getInt("Value",0);
In your main activity onCreate():
SharedPreferences pref = this.getSharedPreferences();
int count = pref.getInt("your key", 0) //0 is default value.
count++;
SharedPreferences.Editor edit = pref.edit();
edit.putInt("your key", count);
edit.commit();
// display current count

Storing data in SharedPreferences accessible to all activities

I want to store and retrieve data that is accessible to all activities in my app using SharedPreferences. Is that possible? Up until now I have been doing it such that the data is stored for a particular activity.
Yes. SharePreferences do exactly this.
In every activity you can this:
SharedPreferences prefs = getSharedPreferences(ApplicationConstants.PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(name, value);
editor.commit();
And then retrieve values in other activty doing this:
mPrefs.getString(name, "");
This is the documentation:
http://developer.android.com/reference/android/content/SharedPreferences.html
And this is a good example to start with:
http://myandroidsolutions.blogspot.it/2012/03/android-preferenceactivity.html
Yes, that's the whole purpose of it.
Here's how you should write to it, via Editor
final SharedPreferences shp = ctx.getSharedPreferences(ctx.getString(R.string.app_name), Context.MODE_PRIVATE);
final SharedPreferences.Editor ed = shp.edit();
ed.putString("var1", "var1");
ed.putString("var2", "var2");
And to load it:
shp.getString("var1", "defvalue");
I have a better version. As sometimes when you try to do getSharedPreferences you might get an error as it could not be found.
This is how I store values in my Android projects.
Add
SharedPreferences sharedPreferences=this.getSharedPreferences("packagename", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("username", "specify name here").apply();
Package Name can be directly copied from top of the activity ex: com.example.name.projectname
Retrieve
String username = sharedPreferences.getString("username","");
If you want to access values in all of your activities I think the better way is storing in a custom Application class and later in activities you can:
((CustomApplication)getApplication()).getStoredValue()
Shared preferences are stored in files and this file access is slower.
Is my example for create function for set and get an object data called "USER"
For set sharePreference data
public void saveUser(User usuario) {
SharedPreferences sharedPref = getSharedPreferences("A", Context.MODE_PRIVATE); // sharedpreference set named "A"
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", usuario.getNombre());
editor.putString("username", usuario.getUsername());
editor.putString("pass", usuario.getContrasena());
editor.putString("roll",usuario.getRol());
editor.commit();
}
For get sharePreference data
public Usuario getUser() {
SharedPreferences sharedPref = getSharedPreferences("A", Context.MODE_PRIVATE); // sharedpreference set named "A"
User usuario = new User();
usuario.setNombre(sharedPref.getString("name", "null"));
usuario.setUsername(sharedPref.getString("username", "null"));
usuario.setContrasena(sharedPref.getString("pass", "null"));
usuario.setRol(sharedPref.getString("roll", "null"));
return usuario;
}
Important: set name to sharePreference in this case "A"

Categories

Resources