1
I am trying to save a display state, where when you press the robot button, a message "True" appears and changes the icon to a person and when I press the person’s icon back to the robot icon and has a message "false"I would like to use Sharedpreference to save the last display state, I would like to know where I am missing, follow the code below:
public class MainActivity extends AppCompatActivity {
TextView testeT;
boolean valorBooleano = false;
SharedPreferences preferences;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testeT = findViewById(R.id.text_teste);
testeT.setText(" " + valorBooleano);
preferences = getSharedPreferences("minhapreferencia", MODE_PRIVATE);
preferences.getBoolean("chave", valorBooleano);
editor = preferences.edit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (valorBooleano == false) {
menu.findItem(R.id.man).setVisible(true);
menu.findItem(R.id.robot).setVisible(false);
} else {
menu.findItem(R.id.man).setVisible(false);
menu.findItem(R.id.robot).setVisible(true);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case (R.id.man):
invalidateOptionsMenu();
testeT.setText(" " + valorBooleano);
valorBooleano = true;
break;
case (R.id.robot):
invalidateOptionsMenu();
testeT.setText(" " + valorBooleano);
valorBooleano = false;
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPause() {
super.onPause();
if (preferences.contains("chave")){
editor.putBoolean("chave", valorBooleano);
editor.commit();
}
}
}
from what I understood there, the value Bostone value is always false. Right?
– Murillo Comino
Oh yes, I was doing some tests, because even removing this false condition it does not work
– Viktor Souza
Check my answer, identify only some problems, if the answer is useful to you, mark as answered and/or useful, if I do not help let me know that I edit my answer.
– Murillo Comino