Android: issue with data storage (SharedPreferences) - android

I'm learning android and for this project I need to save user's data - color change of buttons, in this case -. During the program the change occurs (onClick), but when I restart the app, nothing happens - the change has not been saved (or read...) Can someone help me? Code:
final String paintKey = "paint";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonCreate();
preferences();
togglePlay();
}
public void preferences(){ //the issue in this method?
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
data = settings.getString("stage", "Indoors");
settings.getBoolean(paintKey,false);
String backGround = settings.getString("stage", "Indoors");
if (backGround.equals("Indoors")) {
Picasso.with(this).load(R.drawable.shocked_crowd).fit().centerCrop().into(stage);
}
if (backGround.equals("Street")) {
Picasso.with(this).load(R.drawable.coins).fit().centerCrop().into(stage);
}
}
public void changeColor(){
if(!paint) { //paint variable has global scope and it is set to false
c1.setBackgroundColor(Color.YELLOW);
paint = true;
}else{
c1.setBackgroundColor(Color.BLUE);
paint = false;
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("paint", paint);
editor.commit();
}
EDIT: the onClick method:
public void onClick(View v) {
if(v==color){
changeColor();
}
EDIT: this is how I have it now:
public void preferences(){
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
data = settings.getString("stage", "Indoors");
final String paintKey = "paint";
settings.getBoolean(paintKey,false);
Wrong? if I put editor instead of settings i get red underlined

In order to work with SharedPreferences you need a global key
final String paintKey = "paint"
To write boolean value info SharedPreferences use
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(paintKey, paint).commit();
To read that data later
paint = settings.getBoolean(paintKey, false);

settings.getBoolean(paintKey,false);
This line gets a value from the SharedPreferences and promptly ignores it. You must save the return value in a variable in order to use it later:
boolean paint = settings.getBoolean(paintKey,false);
This will create a local variable that can only be used in the same method. If you need to use the value in other methods, create a field instead.

Related

SharedPreferences saves state between android activities but not upon restarting the app

I'm running to a really weird behavior with SharedPreferences. I'm wondering if I'm running into a synchronization issue.
It seems like the app can remember the preference changes in between activities but not when I restart the app. The state always returns back to the very first instance I created a preference. I've followed several examples, tutorials, and android documentation that all suggest similar code layout. I also watched how the preference.xml file changed while interacting with my code using the debugger and I confirmed it looked like the key value pair updated.
Could I be experiencing a synchronization issue with my emulator? I tried using both the editor.apply() method and editor.commit() method with the same results.
The only thing I've found that fixes my problem is using the editor.clear() method, but this feels a bit hacky...
note: please forgive the variable names, I'm making a pokedex...
public class SecondActivity extends AppCompatActivity {
private boolean caught;
private Set<String> pokemonCaught;
private String pokemonName;
public SharedPreferences sharedPreferences;
public static final String SHARED_PREFERENCES = "shared_preferences";
public static final String PREF_KEY = "inCaughtState";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
/*SKIPPING THE VIEW SETUP*/
/*SKIPPING BUTTON VIEW ATTRIBUTES*/
//variables required for changing button state
pokemonName = (String) nameTextView.getText();
caught = false;
//Loading in sharedPreferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
pokemonCaught = sharedPreferences.getStringSet(PREF_KEY, new HashSet<String>());
if (pokemonCaught.contains(pokemonName)) {
toggleCatch(catchButton);
}
}
public void toggleCatch (View view) {
//Editing and updating preferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (caught == true) {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = false;
pokemonCaught.remove(pokemonName);
}
else {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = true;
pokemonCaught.add(pokemonName);
}
editor.clear(); //This is my hacky solution...
editor.putStringSet(PREF_KEY, pokemonCaught);
editor.apply();
}
}
Try to use SharedPreferences this way:
To save data
SharedPreferences.Editor editor = getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("stringName", "stringValue");
editor.apply();
To retrieve data
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PREFS", MODE_PRIVATE);
String name = preferences.getString("stringName", "none"));
Note that this "none" is in case to string "stringName" be null.

How can I store values from an activity so that I can use them later?

I would like to store a few values from an Activity so that when I navigate away from the activity, they still appear there.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
Button AddButton = (Button) findViewById(R.id.AddButton);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText firstNumEditText = (EditText) findViewById(R.id.firstNumEditText);
EditText secondNumEditText = (EditText) findViewById(R.id.secondNumEditText);
TextView ResultTxtView = (TextView) findViewById(R.id.ResultTxtView);
int num1 = Integer.parseInt(firstNumEditText.getText().toString());
int num2 = Integer.parseInt(secondNumEditText.getText().toString());
int result = num1 + num2;
ResultTxtView.setText(result + "");
}
});
In this case, I only want to save the values of num1, num2 and result. I would like it so that if I navigate back to the main menu, or if I go and do some other app and come back tomorrow, that the values would still be there.
You can store these values by using SharedPreferences.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
Button AddButton = (Button) findViewById(R.id.AddButton);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText firstNumEditText = (EditText) findViewById(R.id.firstNumEditText);
EditText secondNumEditText = (EditText) findViewById(R.id.secondNumEditText);
TextView ResultTxtView = (TextView) findViewById(R.id.ResultTxtView);
int num1 = Integer.parseInt(firstNumEditText.getText().toString());
int num2 = Integer.parseInt(secondNumEditText.getText().toString());
int result = num1 + num2;
ResultTxtView.setText(result + "");
// You can store these values here
// ...
}
});
protected void onResume() {
// And read these values here and set to your ResultTxtView.
// ...
}
You can use shared preferences in your app for saving the data and for using the same data later as mentioned below:
SharedPreferences sp = getSharedPreferences("Data",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name", "Alex");
editor.putString("Email", "alex#gmail.com");
editor.commit();
And then if you want to get the same data in another activity you do this as mentioned below:
SharedPreferences sp= ActvivityA.this.getSharedPreferences("Data",Context.MODE_PRIVATE);
String name = sp.getString("Name");
String email = sp.getString("Email");
This data will be saved till you will not clear the cache of the application or you will not install a new update of the app so in this way you can use this data anywhere in the app.
In this case, I only want to save the values of num1, num2 and result. I would like it so that if I navigate back to the main menu, or if I go and do some other app and come back tomorrow, that the values would still be there.
When you need the values to be persisted across app launches, then Shared Preferences or a data store like SQLite/Room would be the way to go.
Shared Preferences : If the values stored are key value pairs and are limited in size and does not have to scale, then Shared Preference would suit your need.
SqLite : If the data that you store would scale and would become larger in time, then you need to look at a data store like SQLite where you can do Async operations.
create on class which extends Application and create variable to hold specific value and register that class in manifest
in manifest in application tag specify your application class name
public class MyApplication extends Application {
private MyApplication sInstance;
int result;
//write getter setter for result variable same for num1 and num2
#Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
public static MyApplication getInstance() {
return sInstance;
}
}
in onClick set that variable value like MyApplication.getInstnce().setResult();
and in onCreate of set textview value with MyApplication.getInstance().getResult();
Use Following methods for save/retrieve string using SharedPreferences
public static int getIntPreferences(Context context,String key) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
int savedPref = sharedPreferences.getInt(key, null);
return savedPref;
}
public static void saveIntPreferences(Context context,String key, int value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
Save num1,num2 and result using saveIntPreferences when you leave 1st Activity.
After getting back on 1st Activity, you can get saved value using getIntPreferences

Saving the Activity state in android?

Hello guys I've ColorPicker in my app. When I set the color selected by ColorPicker to the Activity background, it works. But when I restart the app, the color changes to default! How to save the state of Activity? Is it possible? Thanks in advance!!!
So for example you can save the color like this (I've just put a hex color reference but you can change it to whatever you wish):
public void setBackgroundColor() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("color", "#FFFFFF");
editor.commit();
}
Then just make sure you call this method every time it loads / reloads:
public void getBackgroundColor() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
if (sharedPreferences.contains("color")) {
String myColor = sharedPreferences.getString("color", null);
mybackground.setBackgroundColor(Color.parseColor(myColor));
}
}
Andy's Answer is correct. However, I thought I would chime in on saving and loading preferences. These are universal Save/Load methods for Strings. It's what I use in all my activities. It can save you a lot of headaches in the future!
public static String PREFS_NAME = "random_pref";
static public boolean setPreference(Context c, String value, String key) {
SharedPreferences settings = c.getSharedPreferences(PREF_NAME, 0);
settings = c.getSharedPreferences(PREF_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
return editor.commit();
}
static public String getPreference(Context c, String key) {
SharedPreferences settings = c.getSharedPreferences(PREF_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME , 0);
String value = settings.getString(key, "");
return value;
}

How do I set up a global variable to share among views in Android?

In one of my views the user makes a selection. I want to store that selection in a variable I can use across all views so it can be used for further database queries such as "bookId".
How can I make "bookId" a global variable that is set on one view and can be accessed across the other views when needed?
----- Edit: What I'm attempting to do based on comments and answers -----
On my main activity where the SharedPreference is stored I have this before the onCreate:
public static final String PREFS_NAME = "myPrefs";
SharedPreferences settings;
Integer bookId;
In my onCreate I've done this:
settings = getSharedPreferences(PREFS_NAME, 0);
bookId = settings.getInt("bookId", 0);
After the button press I'm storing a custom attribute and attempting to set bookId in the SharedPreference:
SharedPreferences.Editor editor = settings.edit();
editor.putInt("bookId",bookKey);
editor.commit();
In another view I'm attempting to get the bookId from the SharedPreference and, for testing purposes, I'm trying to set the stored value to a textView just to make sure it stored and carried over correctly.
Before the onCreate on the second view:
public static final String PREFS_NAME = "myPrefs";
SharedPreferences settings;
Inside the onCreate:
settings = getSharedPreferences(PREFS_NAME, 0);
Integer bookId = settings.getInt("bookId", (Integer) null);
tempBookTextView = (TextView) findViewById(R.id.tempBookTextView);
tempBookTextView.setText(bookId);
I have a two questions, how does this look so far? Any ideas why the app crashes when I use
Integer bookId = settings.getInt("bookId", (Integer) null);
Instead of using global variable to access variable value through out the app try using SharedPreferences.
sample activity:
public class Book extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
String mBookId = null;
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
mBookId = settings.getString("book_id", null);
// use book_id;
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("book_id", mBookId);
// Commit the edits!
editor.commit();
}
}
Preferences are typically created private and can be accessed via all over the application components. Sharing data with other application with world readable or writable preference file is rarely used, as the external component would need to know the exact filename and location of the file.
To kill the spirit of encapsulation,
public class Globals {
public static int x;
public static int y;
}
and later
if (Globals.x == 0) { ... }
But please don't do exactly that, any class can contain static variables, find a class responsible for the value you want to store.
OTOH, android processes may be restarted when you don't expect it, in which case all the variables will be reset. So it's better to use shared preferences and if they don't work as expected (which I have seen in at least one release of Android), store the instance of shared preferences in a static variable.
You can use Shared Preferences
Saved at once !
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(ProjectAct.this).edit();
editor.putInteger(StaticVariable.BOOKID, "1");
p.get("contract_no"));
editor.commit();
Then call from anywhere like that
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
int book_id = prefs.getInteger(StaticVariable.BOOKID,null);
See more at How to use SharedPreferences in Android to store, fetch and edit values

How setup default value Shared Preferences in an android apk?

I make a setup class with shared preferences and in the first open apk the user use the default value and after edit if he want it with update value. My problem is when re open the apk and no create preference apk display default value else if there is old preference display this. I want update preferences onCreate with old save preferences if preferences exist(no with default value). How I create this? I want something if pref exist go to share preference...and read value...else use the default
String strValue ="http://www.power7.net/LEDstate.txt";//default value
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ioweb_bt);
/* SharedPreferences preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
String strValue = preferences.getString("Url","");
text = (TextView) findViewById(R.id.textUrl);
text.setText(strValue);
*/
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
edittxtUrl.setText(strValue);
}
public void Save(View view) {
SharedPreferences preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit(); // Put the values from the UI
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
String strUrl = edittxtUrl.getText().toString();
editor.putString("Url", strUrl); // value to store
// Commit to storage
editor.commit();
Change your code as for setting default value in TextView when user start your Application or any value not exist in SharedPreferences
SharedPreferences preferences;
String strValue="";
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ioweb_bt);
text = (TextView) findViewById(R.id.textUrl);
preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
strValue = preferences.getString("Url","");
if(!strValue.equals("")){
text.setText(strValue);
}
else{
text.setText("Set Default value here");
}
// your code here
In this way, you can get default value from preference if no value is their corresponding to your preference key
SharedPreferences preferences=getSharedPreferences(preferencename, MODE_PRIVATE);
String str=preferences.getString(key, defaultValue);

Categories

Resources