How can I send values to another class without opening it immediately ?
It's like I want to save that value first in another class and I will use that value later.
use SharedPreferences
Example:
SharedPreferences sharedpreferences = getSharedPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("YOUKEY", "YOUR VALUE WANT TO SAVE");
editor.apply(); //OR editor.commit() -_-
to retrieve it
String name = sharedpreferences.getString("YOURKEY",null);
Related
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.
I have a fragment where I let set some SharedPreference values set.
In the fragment, everything works fine - I can get any value I want, saving, editing, deleting works fine.
Then I have an Activity, from where I want to get the value "savedValue1" - but it does not work
public static final String MyPref = "MyPreference";
static SharedPreferences sharedpreferences;
//onCreateView...
sharedpreferences = this.getActivity().getSharedPreferences(MyPref,
Context.MODE_PRIVATE);
editor.putString("savedValue1", someString);
editor.commit();
I tried it with in Fragment:
public static String getValue(){
return sharedpreferences.getString("savedValue1","");
}
in Activity:
String newValue = Fragment.getValue();
But that doesn't work - any hint?
You should not have a Fragment.getValue() method.
SharedPreferences are here to avoid that.
Use the same getSharedPreferences("whatever", Context.MODE_PRIVATE) code and you shall get/set the same values inside the same preferences.
That is how it is supposed to be used. From the official documentation:
For any particular set of preferences, there is a single instance of
this class that all clients share.
Use this code to save and retrieve values from SharedPreferences
//To save string
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor e = settings.edit();
e.putString("savedValue1", someString);
e.commit();
//Retrieve team score
String saved_value = settings.getString("savedValue1", "");
I need to send data Date Display to next Activity and keep that data
private void updateDisplay()
{
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(ShowdatanameActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
mDateDisplay.setText(new StringBuilder().append(mMonth + 1).append("-").append(mDay).append("-").append(mYear).append(" "));
editor.putString("key1", mDateDisplay);
editor.commit();
Intent myIntent = new Intent(ShowdatanameActivity.this,Showdata_result_resume.class);
startActivity(myIntent);
}
Well that's true you can acces to Data/Calendar object from every place of your application. But if you insist:
You've put your string to SharedPreferences under "key1" so in other activity you have to call:
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences("KEY_FOR_YOUR_DATA",ShowdatanameActivity.this);
String data = app_preferences.getString("key1","");
So when you call SharedPreferences you also need key for them. It's some kind of "database version", you can write anything there (i use for example PREFS-KEYv1, and when I need new one I'm incrementing to v2). And don't use same key everywhere it's bad practice.
The other method you could use to send your String to other activity is via intent.
intent.putExtra("key1",yourStringVariable);
and Showdata_result_resume in onCreate after setContent you can get it by:
String data = intent.getExtras().getString("key1");
Using code like this to make preferences code portable between various apps and classes.
from a fragment I get the sharedpref like this. Notice how I have the preferences named in a resource and I use getActivity to get to the preferences.
sharedPref = getActivity().getSharedPreferences(
getString(R.string.preferences), Context.MODE_PRIVATE);
From the main activity I get the sharedpref like this. Notice how I have the preferences named in a resource.
sharedPref = getSharedPreferences(getString(R.string.preferences),
Context.MODE_PRIVATE);
the resource which is shared by all classes in the app.
<string name="preferences">com.gosylvester.hilbilyfashliegt.prefrences</string>
<string name="about_firstrun">com.gosylvester.hilbilyfashliegt.firstrunabout</string>
now to get the data from any class I referer to it with an R string resource.
_Checked = sharedPref.getBoolean(getString(R.string.about_firstrun),
false);
Good Luck
I'm creating a SharedPreferences and it's working only if I start Activity like this:
myIntent.putExtra("prefName", MYPREFS);
startActivity(myIntent);
But my SharedPreferences is not working after I save it and hit back a few times, to go at menu page and go to the page where I want to get my preferences.
Anyone can help me with that?
Code below:
This is where I save my preferences:
String MYPREFS = "MyPref";
SharedPreferences mySharedPreferences;
SharedPreferences.Editor myEditor;
Inside onCreate:
mySharedPreferences = getSharedPreferences(MYPREFS,0);
myEditor = mySharedPreferences.edit();
Inside button onClickListener:
myEditor.putString("address", AddressET.getText().toString());
myEditor.putString("contact", ContactET.getText().toString());
myEditor.commit();
Intent myIntent = new Intent(myContext, nok_individual_particular.class);
myIntent.putExtra("prefName", MYPREFS);
startActivity(myIntent);
This is the activity I pass to:
SharedPreferences mySharedPreferences;
Inside onCreate:
Intent myReceivingIntent = getIntent();
String myPREFName = myReceivingIntent.getStringExtra("prefName");
mySharedPreferences = getSharedPreferences(myPREFName, 0);
applySavedPreferences();
In the applySavedPreferences method:
String addressValue = mySharedPreferences.getString("address", "Jack Smith");
String contactValue = mySharedPreferences.getString("contact", "Jack Smith");
addressTV.setText(addressValue);
contactTV.setText(contactValue);
SharedPreferences: This is how it works
To save your data:
SharedPreferences sPrefs = getSharedPreferences("prefsName", 0);
SharedPreferences.Editor editor = sPrefs.edit();
editor.putString("valueName", "value");
editor.commit();
To retrieve your data:
SharedPreferences sPrefs = getSharedPreferences("prefsName", 0);
String strMyData = sPrefs.getString("valueName", "default value");
The example above is how to set a string and retrieve it.
You are not using SharedPreferences. In your example, you are passing an extra to an activity, but this only makes available the value to the new activity, it doesn't save the value to SharedPreferences.
To use SharedPreferences, you have to do the following:
Save
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("prefName", "String to save").commit();
Get
String value = PreferenceManager.getDefaultSharedPreferences(this).getString("prefName"), "default value");
After mySharedPreferences.edit();
mySharedPreferences.commit();
should be your last line. This enables u to save and close the SharedPreferences file you have edited.
Well, you don't need to pass the sharedprefs in an intent and all. It will be available throughout your application in all activities.
Just call SharedPreferences my_prefs= getSharedPreferences("Pref_name", 0); and then u have a reference to that SharedPreferences file and then u can retrieve values from it.
I prefer using SharedPreferences to save my data and use it throughout my classes , plus they will be saved to the device , making them available even after the app is killed ... Here is an example for ya !
//Some String that I should remember, I am just using the package name for now
String app = this.getPackageName();/*This is going to be used more like a file to save my stuff to*/
//Setting our sharedpreferences
SharedPreferences sha = sha = getApplicationContext().getSharedPreferences(app, SherlockActivity.MODE_PRIVATE);
String myString = "This is the String that you want to save so you can use among your classes"
//Now we call in an editor for that SharedPreferences so we can write and delete stuff from it .
Editor edit = sha.edit();
//Now we insert our String.
edit.putString("Something_you_can_remember" , myString);//You will need the "Something_you_can_remember" a few lines ahead , so remember it !
edit.apply(); //Or we can use edit.commit() , but I prefer apply()
//Now our String is saved ! So lets read it !
String whatever = sha.getString("Something_you_can_remember" , "The String incase myString didn't even exist , saves you from a NullPointerException");
//Here we go ! Now we have our String saved and can be readable among the classes !
//Also , if you wanted to delete that String or whatever you "put" in there , you can call
edit.remove("Something_you_can_remember"); //or edit.clear() to remove all the values stored !
Hope this helps !
Save
SharedPreferences sp = getSharedPreferences("key", 0);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("valueName", "String to save");
sedt.commit();
Get
SharedPreferences sp = getSharedPreferences("key", 0);
String valueName = sp.getString("valueName","");
You do not need to pass SharedPrefences through intents, as SharedPreferences are available to the whole application and any activity has access to it.
You can refer to below example:
Either create SharedPreferences by giving them your choice of name:
SharedPreferences pref = getSharedPreferences("MyPref", MODE_PRIVATE);
OR use default SharedPreferences:
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Use your preference file anywhere in your code by getting them through any of the above methods. No need to pass to different activities.
Once you call any of the above method, if the preference file of that name does not exist for your application, android will create one for you.
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"