I'm trying to learn how to use SharedPrences to save data.
In the test code below, getString returns no value, instead of 'ted', but I cannot figure out why.
public void onCreate(Bundle savedInstanceState) {
SharedPreferences pre=getPreferences(MODE_PRIVATE);
pre.edit().putString("label","ted");
pre.edit().commit();
String tr;
tr=pre.getString("label","no value");
of course both answers are right but dmon's solution is much more easer and short:)
its enough to rewrite your code like this :
public void onCreate(Bundle savedInstanceState) {
SharedPreferences pre=getPreferences(MODE_PRIVATE);
pre.edit().putString("label","ted").commit();
String tr=pre.getString("label","no value");
Easy, edit() creates an Editor. You're putting the value in one and committing in another one. Just save the edit() return value in an Editor variable and call commit() in that.
Could it be because you re-call the edit() function? try this:
public void onCreate(Bundle savedInstanceState) {
SharedPreferences pre=getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = pre.edit();
ed.putString("label","ted");
ed.commit();
String tr;
tr=pre.getString("label","no value");
}
Related
I have a button that increase a variable by one and the result is printed in a TextView. When I rotate the device the variable value is maintained, but if I exit the activity and then re-enter, every value is reset. How can I fix this?
int n=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prova);
final TextView tv = (TextView)findViewById(R.id.tvProva);
Button b = (Button)findViewById(R.id.bProva);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
n++;
tv.setText(""+n);
}
});
if(savedInstanceState!=null){
n = savedInstanceState.getInt("n");
tv.setText(""+n);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("n", n);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getInt("n");
}
There are a couple of potential options.
SharedPreferences, as Tejas said, below is an example of how you might use this;
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
To save you value;
Editor editor = pref.edit();
editor.putInt("n", n);
editor.apply();
To retrieve your value;
pref.getInt("n", 0);
The above was taken from a previous post; https://stackoverflow.com/a/24099496/4644276
Alternatively you could leverage the Repository pattern. A repository in simplest terms is an object that can persist for the life of the application, therefore it can persist across different activities. It cannot however survive killing the application unless you leverage SharePreferences as previously discussed or using an API or local database.
If you'd like to look in to the repository pattern further than it is discussed in the Guide to app architecture page on the Android Developer portal.
https://developer.android.com/jetpack/docs/guide
public class ustawienia extends MainActivity {
EditText kryptonim;
public String test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ustawienia);
kryptonim = (EditText) findViewById(R.id.edit_kryptonim);
test = kryptonim.getText().toString();
}
public String call_back(){
return test;
}
}
When call call_back() from another class I've got error: Unable to start activity ComponentInfo. What's wrong with that?
When you close an activity all data from it is lost, so unless both activities are runing at the same time you can't retrieve data. You could use shared prefrences instead.
// IN ORDER TO WRITE TO A FILE
SharedPreferences.Editor prefs = getSharedPreferences("PrefsName", MODE_PRIVATE).edit();
prefs.putString("test", kryptonim.getText().toString());
prefs.apply(); // use prefs.commit(); if this doesn't work
In order to read data
SharedPreferences prefsR = getSharedPreferences("PrefsName", MODE_PRIVATE); // you could also write 0 instead MODE_PRIVATE
String restoredText = prefsR.getString("test", null);
Ofcourse you need to import SharedPrefs , and put this in oncreate or wherever you want... let me now if it works :)
I have a piece of code that I only want to run the very first time a particular OnCreate() method is called (per app session), as opposed to every time the activity is created. Is there a way to do this in Android?
protected void onCreate(Bundle savedInstanceState) has all you need.
If savedInstanceState == null then it is the first time.
Hence you do not need to introduce extra -static- variables.
use static variable.
static boolean checkFirstTime;
use static variable inside your activity as shown below
private static boolean DpisrunOnce=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run_once);
if (DpisrunOnce){
Toast.makeText(getApplicationContext(), "already runned", Toast.LENGTH_LONG).show();
//is already run not run again
}else{
//not run do yor work here
Toast.makeText(getApplicationContext(), "not runned", Toast.LENGTH_LONG).show();
DpisrunOnce =true;
}
}
use sharedpreference...set value to true in preference at first time...at each run check if value set to true...and based on codition execute code
For Ex.
SharedPreferences preferences = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
if (!preferences.getBoolean("isFirstTime", false)) {
//your code goes here
final SharedPreferences pref = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
}
I am making an application that contains a form and whenever a data clicks a button loads from a BD in a EditText, but every time I press a different button, the other EditText are cleared, I tried with:
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("data", myVariable);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
other = savedInstanceState.getString("data");
name.setText(other);
}
Sorry if I have not explained well, I need that every time they change Activity variables and I have not deleted. Any suggestions? Thank you!
Try using Android SharedPreferences instead. This is a persistent key-value storage that Android offers for its apps and was designed to covers issues like this. Here's the easy way to use it:
SharedPreference prefs = PreferenceManager.getDefaultSharedPreferences(this);
// To put a data (in this case a String from your EditText)..
Editor editor = prefs.edit();
editor.putString("data", yourStringHere);
editor.commit();
...
// ..and to retrieve it..
prefs.getString("data", null);
// NOTE: The 'null' in above method call could be replaced by any String you want;
// it basically specifies a default value to get when "data" is empty or doesn't
// yet exist.
Hope this helps.
Order of calls according to logcat is onCreate, setViewValues, setStrikethroughFlag, (ROTATE), onCreate, setViewValues:
SharedPreferences mSettings;
Editor spEditor;
#Override
public void onCreate(Bundle savedInstanceState) {
....
mSettings = getSharedPreferences("prefs", "")
spEditor = mSettings.edit();
setViewValues();
}
public void setViewValues() {
boolean isStrikeThru = mSettings.getBoolean(STRIKETHROUGH, false);
Log.d("TRACE", "setViewValues, strikethrough " + isStrikeThru);
}
public void setStrikethroughFlag() {
spEditor.putBoolean(STRIKETHROUGH, true);
spEditor.commit();
}
The logcat says setStrikethroughFlag() is called. Then I rotate the screen, onCreate and setViewValues are called. In setViewValues, I thought it would recognize the saved value of STRIKETHROUGH, true. But the logcat trace says the value of isStrikeThru is false.
Try calling the setViewValues() from the Constructor. In Screen orientation change, the oncreate of the activity will gets called again and resets your values.
From know i can see, that you creating local variable in your onCreate()
And in your setViewValues() you accessing your class field variable.
So i am not sure that you are calling getSharedPreferences() on your field variable.
The same is about your spEditor. Fix this and try one more time.
If this will not help you, give as the rest of your code.
UPDATE
Try this mSettings = getSharedPreferences("prefs", Context.MODE_PRIVATE);
The mistake was using quotes around the key when storing my shared preference. The keys didnt match so nothing was persisted, sorry.