Am trying save boolean FAVOURITE data in sharedPreferences. when phone is rotated or closed .It is not working it is taking default value. I don't know whats wrong with this code. i am unable to figure out whats the problem is can someone show me the problem with the code
//Context context =this;
String FAVOURITE = "selected";
boolean favourite = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState!=null){
favourite = savedInstanceState.getBoolean(FAVOURITE,false);
Toast.makeText(this,""+favourite,Toast.LENGTH_SHORT).show();
}
final Bundle queryBundle = new Bundle();
movieObject=(CardsClass)getIntent().getSerializableExtra("movieObject");
setTitle(movieObject.getmTitle());
setContentView(R.layout.activity_details);
final ImageView fav = (ImageView)findViewById(R.id.fav);
fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (favourite == false) {
favourite = true;
fav.setImageResource(R.drawable.fav_on);
Toast.makeText(DetailsActivity.this, favourite + " is added to favourites", Toast.LENGTH_SHORT).show();
queryBundle.putBoolean(FAVOURITE,favourite);
}
else if(favourite){
favourite=false;
fav.setImageResource(R.drawable.fav_off);
queryBundle.putBoolean(FAVOURITE,favourite);
Toast.makeText(DetailsActivity.this, movieObject.getmTitle() + " is removed from favourites", Toast.LENGTH_SHORT).show();
}
}
});
Actually, you're doing the wrong thing. You should do something like:
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(FAVOURITE, favorite); // then you can check the favorite value in onCreate as well.
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
this.favorite = savedInstanceState.getBoolean(FAVOURITE);
// do something here when restore.
super.onRestoreInstanceState(savedInstanceState);
}
To write or read in the SharedPreferences
Write:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(FAVORITE, favorite);
editor.commit();
Read:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Boolean favorite = sharedPref.getBoolean(FAVORITE, true);
Related
I want to save the number value so that when close the app it continues to be saved and when open it the progress is maintained. I don't know why SharedPreferences don't work.
I have tried in many ways but either the app forces it to close or it just doesn't work
number = numero
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView contador;
int numero = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getSharedPreferences("valor", numero);
int data = mPrefs.getInt("valor", numero);
contador = findViewById(R.id.contador);
}
public void onClick(View v) {
numero++;
contador.setText(String.valueOf(numero));
SharedPreferences.Editor data = data.edit();
data.putInt("tag", numero).commit();
}
};
You should use the same sharedPreferences for retrieving the values.
also, get the values by the same key you saved them. below is an example you can follow.
SharedPreferences mPrefs = getSharedPreferences("valor",
Context.MODE_PRIVATE);
try{
int data = mPrefs.getInt("tag", numero);
}
catch(NullPointerException e){
e.printStackTrace()
}
public void onClick(View v) {
numero++;
contador.setText(String.valueOf(numero));
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt("tag", numero).commit();
}
};
I am new to Android development and am having a question about multiple switch buttons, how to retrieve values smartly, and make this data available for other activities?
Currently, I am implemented the save of the button state and retrieval of the information found in the current activity as followed:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
switchButtonOne = findViewById(R.id.switchButtonOne);
switchButtonOne.setChecked(true);
switchButtonTwo = findViewById(R.id.switchButtonTwo);
switchButtonTwo.setChecked(false);
//...... (In total there are 5 switch buttons)
//switchButtonOne
switchButtonOne.setOnCheckedChangeListener((compoundButton, isChecked) -> {
if(isChecked){
stringArrayList.add("1");
}else {
stringArrayList.remove("1");
}
getArray(stringArrayList);
//SAVE
sharedPreferences[0] = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences[0].edit();
editor.putBoolean("1", switchButtonOne.isChecked());
editor.commit();
});
switchButtonOne.setChecked(sharedPreferences[0].getBoolean("1", false));
//switchButtonTwo
switchButtonTwo.setOnCheckedChangeListener((compoundButton, isChecked) -> {
if(isChecked){
stringArrayList.add("2");
}else {
stringArrayList.remove("2");
}
getArray(stringArrayList);
//SAVE
sharedPreferences[0] = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences[0].edit();
editor.putBoolean("2", switchButtonTwo.isChecked());
editor.commit();
});
//.......
}
I am sure there is a more efficient way to implement this and I would gladly appreciate effective resources to learn the best practices of making information and Activity state available between Activities.
Big thanks in advance
One option is to use only one listener for all five buttons. You would do this like so:
public class MyActivity extends Activity implements CompoundButton.OnCheckedChangeListener {
Switch[] buttons;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buttons = new Switch[5];
Switch switchButtonOne = findViewById(R.id.switchButtonOne);
switchButtonOne.setOnCheckedChangeListener(this);
switchButtonOne.setChecked(sharedPreferences[0].getBoolean("1", false));
buttons[0] = switchButtonOne;
Switch switchButtonTwo = findViewById(R.id.switchButtonTwo);
switchButtonTwo.setOnCheckedChangeListener(this);
switchButtonTwo.setChecked(sharedPreferences[1].getBoolean("2", false));
buttons[1] = switchButtonTwo;
//...... (In total there are 5 switch buttons)
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int index;
switch (buttonView.getId()) {
case R.id.switchButtonOne:
index = 0;
break;
case R.id.switchButtonTwo:
index = 1;
break;
...
}
if (isChecked) {
stringArrayList.add(String.valueOf(index + 1));
} else {
stringArrayList.remove(String.valueOf(index + 1));
}
getArray(stringArrayList);
//SAVE
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences[index].edit();
editor.putBoolean(String.valueOf(index + 1), buttons[index].isChecked());
editor.commit();
}
}
At this point the code is not much shorter than yours, however, as soon as you add your other three buttons, you will see than the code for all buttons ends up being considerably shorter and more concise.
It would be great to have a BooleanArray for the SharedPreferences, however, such a class does not exist. A workaround can be found here.
EDIT
Looking at your question and your full code again, I would suggest a different approach. You don't need any OnCheckedChangeListener at all. Simply save the state of your buttons whenever the activity is left (onPause) and restore state once the activity is resumed (onResume). A side effect is that the code gets much shorter.
public class MainActivity extends Activity {
Switch[] buttons;
int numberOfButtons = 5;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
buttons = new Switch[numberOfButtons];
sharedPreferences = getSharedPreferences("YourPreferenceName", MODE_PRIVATE);
for (int i = 0; i < numberOfButtons; i++) {
buttons[i] = findViewById(getResources().getIdentifier("switchButton" + String.valueOf(i + 1), "id", getPackageName()));
}
}
public void onPause() {
super.onPause();
for (int i = 0; i < numberOfButtons; i++) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(String.valueOf(i + 1), buttons[i].isChecked());
editor.apply();
}
}
public void onResume(){
super.onResume();
for (int i = 0; i < numberOfButtons; i++) {
buttons[i].setChecked(sharedPreferences.getBoolean(String.valueOf(i + 1), false));
}
}
}
Please note that, in your layout xml, you have to change the ids of your switches to the following: switchButton1, ..., switchButton5.
You can Implement CompoundButton.OnCheckedChangeListener for whole activity and then set listener for all switch you have used.Handle all switch in single callback onCheckedChanged.
public class SwitchActivity extends Activity implements CompoundButton.OnCheckedChangeListener {
Switch switchButtonOne;
Switch switchButtonTwo;
#Override
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
switchButtonOne = findViewById(R.id.switchButtonOne);
switchButtonOne.setChecked(true);
switchButtonTwo = findViewById(R.id.switchButtonTwo);
switchButtonTwo.setChecked(false);
switchButtonOne.setOnCheckedChangeListener(this);
switchButtonTwo.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.switchButtonOne:
//Handle Code for switchButtonOne
break;
case R.id.switchButtonTwo:
//Handle Code for switchButtonOne
break;
}
}
}
I am trying to save the value of swipesRemaining via the SharedPreferences interface. The value of the variable does not persist. I'm not sure what I am doing wrong.
Here is the source code:
public class MainActivity extends AppCompatActivity {
private TextView swipes;
private int swipesRemaining = 11;
private static final String SWIPES = "swipes";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipes = (TextView) findViewById(R.id.textView);
loadInt();
if(savedInstanceState != null) {
swipesRemaining = savedInstanceState.getInt(SWIPES);
}
updateText(swipesRemaining);
}
public void save(View view) {
saveInt("key", swipesRemaining);
}
public void reset(View view) {
swipesRemaining = 11;
updateText(swipesRemaining);
}
public void swipe(View view) {
if(swipesRemaining > 1) {
swipesRemaining--;
updateText(swipesRemaining);
} else {
Toast toast = Toast.makeText(this, "You ran out of swipes!...Resetting", Toast.LENGTH_SHORT);
toast.show();
reset(view);
}
}
private void updateText(int swipesRemaining) {
swipes.setText("Swipes: " + swipesRemaining);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt(SWIPES, swipesRemaining );
super.onSaveInstanceState(savedInstanceState);
}
private void saveInt(String key, int value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
private void loadInt() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
swipesRemaining = sharedPreferences.getInt("key", swipesRemaining);
Toast toast = Toast.makeText(this, "Swipes left: " + swipesRemaining, Toast.LENGTH_SHORT);
toast.show();
}
}
How to return seekBar value from Activity B to Activity A ?
seekBar=(SeekBar)findViewById(R.id.seekBarPercentage);
save.setOnClickListener(new View.OnClickListener() //return to previous activity {
#Override
public void onClick(View v) {
Intent returnIntent=new Intent();
Project=project.getSelectedItem().toString(); //spinner value
Description=description.getText().toString(); //editText value
// seekBar value ?
returnIntent.putExtra("Project",Project);
returnIntent.putExtra("Description",Description);
setResult(Activity.RESULT_OK,returnIntent);
}
});
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progress = 0;
#Override
public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
progress = progresValue;
// Toast.makeText(getApplicationContext(), "Changing seekbar's progress", Toast.LENGTH_SHORT).show();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Toast.makeText(getApplicationContext(), "Started tracking seekbar", Toast.LENGTH_SHORT).show();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
progressText.setText("Covered: " + progress + "/" + seekBar.getMax());
// Toast.makeText(getApplicationContext(), "Stopped tracking seekbar", Toast.LENGTH_SHORT).show();
}
});
}
Additionally to #Anindya Dutta's Answer if you want to persist the data use SharedPreferences
Get SharedPreferences
SharedPreferences prefs = getDefaultSharedPreferences(context);
Read preferences:
String key = "test1_string_pref";
String default = "returned_if_not_defined";
String test1 = prefs.getString(key, default);
To edit and save preferences
SharedPreferences.Edtior editor = prefs.edit(); //Get SharedPref Editor
editor.putString(key, "My String");
editor.commit();
Shorter way to write
prefs.edit().putString(key, "Value").commit();
Additional info for SharedPreferences: JavaDoc and Android Developers Article
Keep the int progress outside the OnSeekBarChangeListener.
Retrieve current progress as progress = seekBar.getProgress().
Similar to returnIntent.putExtra("Description",Description);, put the progress in the Intent as an extra.
I have a list of objects which need to persist should the user minimize the app. Is there any way to do this without using SharedPreferences or an SQLite database (seems like overkill for a single list)?
Have the object implement Parclable or Serializable
Then you can just put it in the Bundle
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(key, value);
}
And get it back in onCreate(),onRestoreInstanceState() depending on your needs.
Using a tutorial I found here, I implemented it using SharedPreferences, the main difference was that instead of using a key ,"MEM1", I use an Index. When my activity loads, I can check the size of the index using this code,
for(int x =0; ;x++) {
index = x;
if(sharedPreferences.contains(String.valueOf(x))){
temp = gson.fromJson(sharedPreferences.getString(String.valueOf(x), null), PointOfInterest.class);
pointList.add(temp);
}
else {
break;
}
}
Example:
public class AndroidSharedPreferencesEditor extends Activity {
EditText editText1, editText2;
TextView textSavedMem1, textSavedMem2;
Button buttonSaveMem1, buttonSaveMem2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textSavedMem1 = (TextView)findViewById(R.id.savedmem1);
textSavedMem2 = (TextView)findViewById(R.id.savedmem2);
editText1 = (EditText)findViewById(R.id.edittext1);
editText2 = (EditText)findViewById(R.id.edittext2);
buttonSaveMem1 = (Button)findViewById(R.id.save_mem1);
buttonSaveMem2 = (Button)findViewById(R.id.save_mem2);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
buttonSaveMem2.setOnClickListener(buttonSaveMem2OnClickListener);
LoadPreferences();
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM1", editText1.getText().toString());
LoadPreferences();
}
};
Button.OnClickListener buttonSaveMem2OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM2", editText2.getText().toString());
LoadPreferences();
}
};
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
String strSavedMem2 = sharedPreferences.getString("MEM2", "");
textSavedMem1.setText(strSavedMem1);
textSavedMem2.setText(strSavedMem2);
}
}