SharedPreferences not working. Always show the same value - java

This is my MainActivity.java's onCreate method:
protected void onCreate(Bundle savedInstanceState) {
loadSavedPreferences();
savePreferences("storedAddress", userAddress.getText().toString());
}
These 2 are the methods inside the class
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String address = sharedPreferences.getString("storedAddress", "YourAddress");
userAddress.setText(address);
}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
Here's the flow. First time user uses the app has to enter their address in the EditText field. I want the same address to be stored there when the user returns.
The problem with the code above: It always shows "YourAddress" in the EditText field. There's no login required for this application. Just a simple form.

Use your savePreferences() method in any action the user can do after typing his address,a button click or whatever.
The way it is now, it's saving only when the activity gets created and after you load the preferences with the default value YourAddress. That's why you always get the same value.

Related

SharedPreferences automatically save text from TextView without a Save button

I have a problem that should remember-save the text from the TextView that the user inputs through his voice, but I have enabled the Night mode, at the time when the day mode passes into the night mode, the text entered at that moment disappears. I know that it needs to be SharedPreferences, I tried this code, but I can not record anything. I emphasize that there is no Save button. It is necessary to return the text already entered when refreshing the Activity. I ask for help please
/*...*/{
//...
myText = (TextView) findViewById(R.id.textView);
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (!TextUtils.isEmpty(restoredText)) {
myText.setText(restoredText);
}
//...
}
public void loadData() {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("text", myText.getText().toString());
editor.commit();
}
It sounds like your activity is getting killed. If this is the case, then you should implement the android activity lifecycle methods onSaveInstanceState and onRestoreInstanceState.
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(bundle);
state.putString("text", myText.getText().toString());
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
myText.setText(savedInstanceState.getString("text"));
}

SharedPreferences not updated

I'm trying to create a simple Settings Activity with a single setting to change the language of the App.
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/locale">
<ListPreference
android:key="lang"
android:title="#string/language"
android:summary="#string/languageDesc"
android:entries="#array/languages"
android:entryValues="#array/languageValues"
android:defaultValue="#string/locale_en"/>
</PreferenceCategory>
public class TCPreferenceActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("lang")) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("lang", sharedPreferences.getString(key, "en_US"));
editor.commit();
settings();
}
}
public void settings() {
Intent intent = new Intent(this, TCPreferenceActivity.class);
intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT, TCPreferenceFragment.class.getName());
intent.putExtra(PreferenceActivity.EXTRA_NO_HEADERS, true);
startActivity(intent);
}
#Override
protected void attachBaseContext(Context newBase) {
SharedPreferences pref = newBase.getSharedPreferences("lang", MODE_PRIVATE);
String lang = pref.getString("lang", null);
Locale locale = new Locale(lang);
Context context = TCContextWrapper.wrap(newBase, locale);
super.attachBaseContext(newBase);
}
}
When I debug the activity, i see the updated value being received in the method onSharedPreferenceChanged.
However when i call the Intent to reload the activity, with the context wrapper in order to change the language, the value received from the call to newBase.getSharedPreferences("lang", MODE_PRIVATE) is still the original unchanged value.
When i click again on the preference in the interface, i see that the value hash changed.
Do I need to save the value?
Why doesn't it changed in the SharedPreferences class?
I'm trying to replicate what0s being done in the exemple here:
Android context.getResources.updateConfiguration() deprecated
Thanks in advance.
Try changing:
SharedPreferences pref = newBase.getSharedPreferences("lang", MODE_PRIVATE);
To:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(TCPreferenceActivity.this);
For what ever reason, you are loading up private "lang" preferences, which im pretty sure you are not saving to. Use the default preferences instead which the activity should be by default using else where.
I would rather that you user apply() instead of commit().
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk.
Do this;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("lang", sharedPreferences.getString(key, "en_US"));
editor.apply();

How to Set Values in Shared Preferences using Java in Android?

here is the Method:
public class SessionManager {
public static void setStatus(Context context, int value, String key) {
// TODO Auto-generated method stub
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = pref.edit();
editor.putInt(key,value);
editor.commit();
}
public static int getStatus(Context c,String key){
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(c);
int a = pref.getInt(key,0);
return a;
}
}
i am trying to set value "1" in shared Preferences on PostExecuteMethod() of Async Task:
protected void onPostExecute(Void result){
super.onPostExecute(result);
progressDialog.dismiss();
Log.i("Setting Status Variables Value in Customer:",""+AndroidUtil.getStatusForServices());
SessionManager.setStatus(context,1,"status");
Log.i("Setting Status Variables Value in Customer after:",""+AndroidUtil.getStatusForServices());
}
But it still it saves 0 in Variable Here is the Logcat:
01-04 03:31:32.430: I/Setting Status Variables Value in Customer:(20879): 0
01-04 03:31:32.440: I/Setting Status Variables Value in Customer after:(20879): 0
You can easily do this in the following way.
First you will need declare the SharedPreferences inside the Activity in this manner:
public class MainActivity extends Activity
{
SharedPreferences sp;
int val=2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp=this.getSharedPreferences("service_validation", MODE_WORLD_READABLE);
val=sp.getInt("VALIDATION", val);
.
.// you can put here anything code
.
}
.
.// you can put here anything method
.
.
}
Now when you would like to save the value in background asynch task. Please put this code inside onPostExecute(..) method in this manner:
SharedPreferences.Editor editor=sp.edit();
editor.putInt("VALIDATION", 1);
editor.commit();
It is better to use this code on doInBackground(..) method.
After saving the value, refresh or re-run the Activity. It will show the effect .
Enjoy the code!!
If my answer will help you then please support my answer.

boolean won't stay on the right input when i kill my app or reboot the device

im building a app, found a java part that lets me show an activity only at first start.
this works but when i kill the app or reboot my phone it goes back, can anyone help me out with this?
im using this in my main activity (Toolz.java)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Prefs.firststart == false) {
setContentView(R.layout.toolz);
} else {
Intent i = new Intent(this, First.class);
startActivity(i);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
and i added this to First.java
Prefs.firststart=false;
and i made the Prefs.java and added this
public class Prefs {
public static boolean firststart = true;
}
you will need to use SharedPreferences instead o static variable for saving data which also available when app killed or device reboot.
you can see following tutorial how we use SharedPreferences for saving and reading data from SharedPreferences
Shared Preferences
When the app restarts all your code will start from the starting point (i.e Prefs.firststart will be set to true). Instead, you need to make a persistent variable that is saved throughout sessions. If you're using a DB you could use that, or you could use the built-in SharedPreferences, as such:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = this.getPreferences(MODE_PRIVATE);
if (prefs.contains("started")) {
setContentView(R.layout.toolz);
} else {
//Add the preference:
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("started",true);
editor.apply();
Intent i = new Intent(this, First.class);
startActivity(i);
finish();
}
}
When you kill your app, the values are going to reset to their initial values. Your boolean will be equal to true. I suggest saving the state of the variable using SharedPreferences. Check out this other question someone asked about saving.
How to save a state of a variable in android app and use it
Try it like this
//**** First start *****
//you get the prefs for your app using a pref name
String PREFS_NAME = "myAppPrefs";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
//persist the boolean value in preferences using a key-value approach
editor.putBoolean("pref_app_started", true);
//commit the changes
editor.commit();
and when you start the app you check for that pref
//**** next start *****
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//now we get the saved boolean using the key we previously uesd when setting it
//the second parameter is the default value for the flag in case it was never set
boolean wasAppStarted = settings.getBoolean("pref_app_started", false);
//now you can use your wasAppStarted flag to decide what you do further

How do I return stored preferences from another activity in Android?

I cant seem to return a string to an activity in my android application from shared preferences.
In my UI class I have this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
format = preferences.getString("BallPref", "number");//not sure what needs to be in value
in Preferences.xml I have this:
<ListPreference
android:name="BallDisplayPreference"
android:key="BallPref"
android:summary="Show numbers or notes on balls"
android:title="Balls"
android:defaultValue="Fret"
android:entries="#array/listArray"
android:entryValues="#array/listValues" />
In the settings class I have this:
public class Settings extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("BallPref", "Fret"); // value to store
editor.commit();
}
What I want to do is go into settings, and select my string option. then i want to find out what the user selected when the game starts. this doesn't seem to be working, any ideas on where I am going wrong?

Categories

Resources