My sharedpreferences does not save if i re-open my game the data that i saved before with SharedPreferences are not load, setting on my current activity is back to normal again or default
this is the image of my button in menu.class
this is the following code of my menu.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.menu);
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Lifes", 6);
editor.putInt("Hints", 6);
editor.putInt("Level", 1);
editor.commit();
f1=(Button)findViewById(R.id.f1);
f2=(Button)findViewById(R.id.f2);
f2lock=(ImageView)findViewById(R.id.f2lock);
f1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent i =new Intent(menu.this, levelone.class);
startActivity(i);
}
});
f2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent i =new Intent(menu.this, leveltwo.class);
startActivity(i);
}
});
f3=(Button)findViewById(R.id.f3);
f3lock=(ImageView)findViewById(R.id.f3lock);
}
public void onResume() {
super.onResume();
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
levelunlocked = pref.getInt("Level", 0);
if(levelunlocked == 2)
{
f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
if(levelunlocked == 3)
{
f3.setVisibility(View.VISIBLE);
f3lock.setVisibility(View.GONE);
}
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Level", levelunlocked);
editor.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splashscreen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and i had this code in levelone.class to get the default value from menu.class
int gamelifes, gamehints, gamelevel, index=0;
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
gamelifes = pref.getInt("Lifes", 0);
gamehints = pref.getInt("Hints", 0);
gamelevel = pref.getInt("Level", 0);
//the value from sharedpreferences is use to be a text by use code below
lifes1 =(TextView)findViewById(R.id.lifestext1);
lifes1.setTextColor(Color.RED);
lifes1.setText(String.valueOf(gamelifes));
hints1 =(TextView)findViewById(R.id.hintstext1);
hints1.setTextColor(Color.GRAY);
hints1.setText(String.valueOf(gamehints));
and to save the sharedpreferences with new data
String answer=edittextanswer1.getText().toString();
if(answer.equalsIgnoreCase(answer1[index]))
{
gamelevel++;
image.setVisibility(View.GONE);
finishbutton.setVisibility(View.VISIBLE);
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Lifes", gamelifes);
editor.putInt("Hints", gamehints);
editor.putInt("Level", gamelevel);
editor.commit();
else
{
tryagain1.setVisibility(View.VISIBLE);
gamelifes--;
lifes1.setText(String.valueOf(gamelifes));
}
then if finish button is clicked it will be like this
finishbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
finish();
}
});
so levelone.class are finish and back to menu.class
and SharedPreferences code its worked properly, every button in my menu.class work with the code and be visible!
but if i exit the application, its back to normal again
anyone have a solution to fix my problem here?
You have the following lines in your onCreate method :
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Lifes", 6);
editor.putInt("Hints", 6);
editor.putInt("Level", 1);
editor.commit();
The onCreate method is run every time needed by the actvity lifecycle. Especially when openning the app. So everytime your activity is created you set the preference level to one. This is the reason of your issue.
Thing is, on your onCreate() method you're always resetting the shared preferences here:
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Lifes", 6);
editor.putInt("Hints", 6);
editor.putInt("Level", 1);
editor.commit();
Just check if this file exists already before that line with an if statement. That should do the trick.
Something like:
if (pref.contains("Level")) {
// Do not reset
}
else {
// Create the prefs
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Lifes", 6);
editor.putInt("Hints", 6);
editor.putInt("Level", 1);
editor.commit();
}
You don't have to check for that exact field, it's just an example. Adjust it for your needs and game logic.
Take a look at the Activity lifecycle to understand why this is happening.
(diagram source)
Everytime you open your app, the onCreate() method is called, so your prefs get reset before you read them.
More on the lifecycle here.
EDIT: The following snippet shows one way to solve your problem.
public static final String PREF_LIFES = "Lifes";
public static final String PREF_HINTS = "Hints";
public static final String PREF_LEVEL = "Level";
public static final String PREF_IS_SET = "isSet";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.menu);
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
// Check wether the pref is set or not.
if (pref.getBoolean(PREF_IS_SET.false)) {
// The prefs is set. Do some game logic here. Like checking for lifes.
if (pref.getInt(PREF_LIFES,0) == 0) {
// Player is "dead", reset it.
resetPrefs(pref);
}
else {
// Player is alive, do whatever you want, or do nothing at all.
}
}
else {
// if it's not set, just create it.
resetPrefs(pref);
}
// ...
}
private void resetPrefs(SharedPreferences pref) {
SharedPreferences.Editor editor = pref.edit();
editor.putInt(PREF_LIFES, 6);
editor.putInt(PREF_HINTS, 6);
editor.putInt(PREF_LEVEL, 1);
editor.putBoolean(PREF_IS_SET,true);
editor.commit();
}
EDIT 2: You can put this logic on your onResume() method as well, as long as you remove it from the onCreate(), otherwise you'll be checking those conditions twice ;)
i think you didn't check the existence values of shared Preferences in Menu.class.You just simply assign a default value without proper checking whether the sharedpreferences holds data or not.
In onCreate
try this one on OnCreate of Menu.class
SharedPreferences.Editor editor = pref.edit();
//check it with your default value.I used default value as 0
int lifes=pref.getInt("Lifes", 0);
if(lifes==0)
editor.putInt("Lifes", 6);
//check it with your default value.I used default value as 0
int hints=pref.getInt("Hints", 0);
if(hints==0
editor.putInt("Hints", 6);
//check it with your default value.I used default value as 0
int level=pref.getInt("Level", 0);
if(level==0)
editor.putInt("Level", 1);
editor.commit();
This happens because when you start your app your menu.class reset or commit the shared preferences data by your code in menu.class file onCreate() like this :
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Lifes", 6);
editor.putInt("Hints", 6);
editor.putInt("Level", 1);
editor.commit();
You need to check first if shared preferences already available with your shared preferences name, if no then initialise shared preferences code like this :
if() // Check your shared preferences already not available then initialise it
{
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Lifes", 6);
editor.putInt("Hints", 6);
editor.putInt("Level", 1);
editor.commit();
}
Everytime you create your Activity, you are reseting your saved Preferences:
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Lifes", 6);
editor.putInt("Hints", 6);
editor.putInt("Level", 1);
editor.commit();
You should only save your Preferences when they are changed.
Related
Intent intent1 = new Intent(Questions.this, Questions.class);
startActivity(intent1);
Little problem in my learning.
Sorry for my frenchglish ^^
A variable changes every time, i press a button, it backs up and assigns it ++.
In the button input if the variable == in table REPONSE.Length, It restarts the activity and it REMOVE the backup.
My problem is that the backup does not remove itself while the activity restarts well.
Every time i support the activity it raises again without being able to start again at stage 0.
int REPONSE[]= new int[5]; //tableau des reponses
int Question = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questions);
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Question = sharedPreferences.getInt("num", 0);
cardView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Restart si Question == REPONSE.length
if (Question == REPONSE.length){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("num");
editor.apply();
Intent intent1 = new Intent(Questions.this, Questions.class);
startActivity(intent1);
}
//Sauvegarde de la variable
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("num", Question++);
editor.apply();
//Incrementation +1
Question++;
}
}); }
Thanks in advance:)
According to the documentation remove() removes a value once commit() is called. So you have to change editor.apply() to editor.commit()
//Restart si Question == REPONSE.length
if (Question == REPONSE.length){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("num");
editor.commit(); //editor.apply() won't work
There are 3 points that I wold recommend you:
Point 1:
Try giving your Shared preference a name. Example:
sharedPreferences = getSharedPreferences("sharedPrefName", MODE_PRIVATE);
If you are not giving a name to the shared preference android can fall into ambiguity and create a new Sharedpreference thus not affecting the old one.
Even you are creating a new SharedPreference inside the onClick method(this process is wrong), and there the android system is not being able to understand which Shared Preference to use thus not affecting the sharedpreference data that you want to change.
Point 2:
This not so important as the first one but to change the data of an already existing preference you need not to delete the preference instead just change the value, and it will be updated to your requirement:
sharedPreferences.edit().putInt("num", Question++).apply();
Point 3:
Create SharedPreference object once inside the class where it can
have global scope.
Initialize the SharedPreference only once in an activity inside
onCreate method.
Make your code something like this:
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
ConstraintLayout layout;
int Question = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
layout = findViewById(R.id.layout);
sharedPreferences = getSharedPreferences("sharedPrefName", MODE_PRIVATE);
Question = sharedPreferences.getInt("num",0);
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferences.edit().putInt("num", Question++).apply();
}
});
}
}
I'm using DefaultSharedPrefeneces to save and load the state of the checkboxes in my navigation drawer.
when the navigation drawer is created and the state of the checkboxes are loaded from the DefaultPreferences, if the booleans for each checkbox are true then the checkboxes are set to checked.
when the user clicks on a checkbox the state then get saved to the defaultsharedPrefences.
I have no problem with all this.
the problem is that then i try to put 2 booleans into the defaultsharedprefences before the commit it doesn't work and appears to overwrite the first boolean.
Here is my code
//Navigation Drawer
private void addDrawerItems() {
String[] osArray = {"item1", "item2", "item3"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, osArray);
if (mIsPremiumUser) {
mDrawerList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
} else {
mDrawerList.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
}
mDrawerList.setAdapter(mAdapter);
Boolean isCheckedValue;
// *** THIS IS WHERE I LOAD THE CHECKBOX STATE FROM DEFAULTSHAREDPREFERENCES ***
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
isCheckedValue = preferences.getBoolean("cbox1", false);
mDrawerList.setItemChecked(0, isCheckedValue);
isCheckedValue = preferences.getBoolean("cbox2", true);
mDrawerList.setItemChecked(1, isCheckedValue);
isCheckedValue = preferences.getBoolean("cbox3", true);
mDrawerList.setItemChecked(2, isCheckedValue);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckedTextView ctv = (CheckedTextView) view;
if (!mIsPremiumUser) {
Toast.makeText(getApplication(), "Upgrade", Toast.LENGTH_LONG).show();
return;
}
switch (position) {
case 0:
if (ctv.isChecked()) {
requestActivityUpdates();
Toast.makeText(getApplicationContext(), "item1ON", Toast.LENGTH_SHORT).show();
// THIS IS WHERE I SAVE THE STATE OF THE CHECKBOX IN DEFAULT SHAREDPREFENCES
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cbox1", ctv.isChecked());
editor.commit();
} else {
removeActivityUpdates();
Toast.makeText(getApplicationContext(), "item1OFF", Toast.LENGTH_SHORT).show();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cbox1", false);
editor.commit();
}
break;
case 1:
if (ctv.isChecked()) {
Toast.makeText(getApplicationContext(), "item2 ON", Toast.LENGTH_LONG).show();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
// THIS IS WHERE I SAVE THE STATE OF THE CHECKBOX IN DEFAULT SHAREDPREFENCES
editor.putBoolean("cbox2", ctv.isChecked());
editor.putBoolean("callStatus", ctv.isChecked()); // << THIS LINE IS CAUSING ME PROBLEMS
editor.commit();
} else {
Toast.makeText(getApplicationContext(), "item2 OFF", Toast.LENGTH_LONG).show();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cbox2", ctv.isChecked());
editor.putBoolean("callStatus", ctv.isChecked());
editor.commit();
}
break;
case 2:
if (ctv.isChecked()) {
Toast.makeText(getApplicationContext(), "item3 ON", Toast.LENGTH_LONG).show();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cbox3", ctv.isChecked());
editor.putBoolean("smsStatus", ctv.isChecked());
editor.commit();
} else {
Toast.makeText(getApplicationContext(), "item3 OFF", Toast.LENGTH_LONG).show();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("cbox3", ctv.isChecked());
editor.putBoolean("smsStatus", ctv.isChecked());
editor.commit();
}
break;
}
}
});
}
I know for sure that it works for one putBoolean on each item clicked, but doesn't when I've two putBoolean within the same if/else before a editor.commit .
any suggestions on whats causing the problem and how to fix it ? would be greatly appreciated it.
I figured it out!
as the boolean were being stored in an external defaultSharedPrefenences file,
outside of the app the values were always being read in from that.
the state would be pulled the last time i clicked on the check boxes.
I was thinking that each time I i force closed the app it would go back to the default selections states that i wanted which was false,true,true. but as the default Sharedpreferences was not destroyed when the app was it would load in the most recent state.
I had to clear the app data in the application manager in order for it set the boolean back to null, and display false,true,true.
I'm trying use two SharedPreferences, the firt is Working, but the second isn't
here is my Java Code
public class JogoActivity extends AppCompatActivity implements View.OnClickListener {
//OTHERS VARIABLES
public TextView txtViewResult,txtCoins, txtTentativas;
private static final String PREF_NAME = "JogoActivityPreferences";
int resulFinalCache,coinsFinalCache;
int count1, count2 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Configuration config = getResources().getConfiguration();
//methods...
//MY PROBLEMS START HERE
txtCoins = (TextView) findViewById(R.id.txtCoins);
txtViewResult = (TextView) findViewById(R.id.textViewResultado);
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
count1 = sp1.getInt("count1", 0);
txtViewResult.setText(String.valueOf(formatter.format(count1).toString()));//THIS IS WORKING
SharedPreferences sp2 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
count2 = sp2.getInt("count2", 0);
txtCoins.setText(String.valueOf(formatter.format(count2).toString()));////THIS ISN'T
}
//Creating methods...
#Override
protected void onStop(){
super.onStop();
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS IS WORKING
count1 = sp1.getInt("count1", 0);
SharedPreferences.Editor editor = sp1.edit();
editor.putInt("count1", resulFinalCache);
editor.commit();
SharedPreferences sp2 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS ISN'T
count2 = sp2.getInt("count2", 0);
editor = sp1.edit();
editor.putInt("count2", coinsFinalCache);
editor.commit();
}
#Override
public void onDestroy() {
super.onDestroy();
SharedPreferences sp1= getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS IS WORKING
SharedPreferences.Editor editor = sp1.edit();
editor.putInt("count1", resulFinalCache);
editor.commit();
SharedPreferences sp2= getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS ISN'T
editor = sp2.edit();
editor.putInt("count2", coinsFinalCache);
editor.commit();
}
}
every time I launch the app, I use, I close the app and open again, the TextView txtViewResult is working fine, but the txtCoins isn't
I Try use just getPreferences and not getSharedPreferences, but it isn't work too
I try create other Editor, but it isn't work too
Did i do something wrong?
Thank you very much!
No need to call getsharedpreferences twice.
Just call it one time and it should be working fine.
E.g your onstop would be
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS IS WORKING
count1 = sp1.getInt("count1", 0);
SharedPreferences.Editor editor = sp1.edit();
editor.putInt("count1", resulFinalCache);
count2 = sp1.getInt("count2", 0);
editor.putInt("count2", coinsFinalCache);
editor.commit();
hmm. your solution is
SharedPreferences sp1_2 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
count1 = sp1_2.getInt("count1", 0);
SharedPreferences.Editor editor = sp1_2.edit();
editor.putInt("count1", resulFinalCache);
editor.commit();
count2 = sp1_2.getInt("count2", 0);
editor = sp1_2.edit();
editor.putInt("count2", coinsFinalCache);
editor.commit();
//now both will work
infact bind the methods
Don't use the same name when getting them!
Instead of
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences sp2 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
Use two different names like so:
SharedPreferences sp1 = getSharedPreferences(PREF_NAME1, MODE_PRIVATE);
SharedPreferences sp2 = getSharedPreferences(PREF_NAME2, MODE_PRIVATE);
Also you don't need two different shared preferences. Just use one and put those 2 values with different keys.
Generally i can advise you to use simply
For saving:
PreferenceManager.getDefaultSharedPreferences(this).edit().putInt("name", 1).apply();
For reading:
PreferenceManager.getDefaultSharedPreferences(this).getInt("name", 0);
Enjoy!
I have a code... Its excellent save data and load data, but... When i reset application, my score loading, but when i click button for +5 score, my score reset and set 5. I am want that addition +5, but its dont work...
I understand that the problem of addition, because save and load working excellent, but addition doesnt work.
Sorry for my bad English :)
int mCounts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appli);
Settings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
int mCounts = Settings.getInt(APP_PREFERENCES_SCORE, 1);
score = (TextView) findViewById(R.id.score);
score.setText(String.valueOf(mCounts));
}
public void five(View view) {
score.setText(String.valueOf(mCounts += 5)+"");
}
public void onPause() {
super.onPause();
SharedPreferences.Editor editor = Settings.edit();
editor.putInt(APP_PREFERENCES_SCORE, mCounts);
editor.apply();
}
Try this code in your button:
public void five(View view) {
score.setText(String.valueOf(mCounts += 5)+"");
SharedPreferences.Editor editor = Settings.edit();
editor.putInt(APP_PREFERENCES_SCORE, mCounts);
editor.apply();
}
Problem is here:
int mCounts = Settings.getInt(APP_PREFERENCES_SCORE, 1);
Remove int. it will work
I have a toggle that change the brightness in my device from manual to authomatic. It works but the state of button doesn't save.. There are two things i need right now.
1) Save the button state using sharedpreferences
2) Check when i open the application which kind of brightness there is in the phone.
This is the toggle in my onCreate:
autoBrightToggle = (ToggleButton)v.findViewById(R.id.luminosita);
autoBrightToggle.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (autoBrightToggle.isChecked()) {
setAutoBrightness(true);
} else {
setAutoBrightness(false);
}
}
});
and the method:
void setAutoBrightness(boolean value) {
if (value) {
Settings.System.putInt(getActivity().getContentResolver(), SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
} else {
Settings.System.putInt(getActivity().getContentResolver(), SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_MANUAL);
}
}
i tryied in this way but not works:
sPrefdata = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
ToggleButton autoBrightToggle = (ToggleButton) findViewById(R.id.brightoggle); //Dichiaro il toggle
boolean togglebrightness = sPrefdata.getBoolean("DATA", false); a
if (togglebrightness ) //if (tgpref) may be enough, not sure
{
autoBrightToggle .setChecked(true);
}
else
{
autoBrightToggle .setChecked(false);
}
and so in the onClick
SharedPreferences sPref = getSharedPreferences(PREFS_NAME, 0);
Editor editor = sPref.edit();
editor.putBoolean("DATA", true); //or false
editor.apply();
but doesn't work. Doesn't save the state and the method stops works. How can i solve? And how can i check which is the actual brightness?
Try the snippet given below, I've used it to save strings in shared preferences.
SharedPreferences.Editor ed = getSharedPreferences("DATA", 0).edit();
ed.putBoolean("DATA", true);
ed.commit();