I'm new to android development and I'm trying to learn SharedPreferences. How do I manipulate the value of X using buttons and then save it to SharedPreferences again using a button.
I have to declare SharedPreferences after OnCreate, but if I declare X after OnCreate I have to set it Final so I can use it in my onClickListener, because it's inner class, but if I do then I'd get a complier error that reads:
"Error:(42, 17) error: cannot assign a value to final variable x"
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
final Editor editor = pref.edit();
int x = pref.getInt("Value", 0);
final TextView txt = (TextView) findViewById(R.id.textView);
final Button ButtonAdd = (Button) findViewById(R.id.buttonPlus);
final Button ButtonMinus = (Button) findViewById(R.id.buttonMinus);
final Button ButtonCommit = (Button) findViewById(R.id.buttonCommit);
final EditText EditText = (EditText) findViewById(R.id.editText);
txt.setText(Integer.toString(x));
ButtonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
x = x + 1;
EditText.setText(Integer.toString(x));
}
});
ButtonMinus.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if(x != 0){
x=x-1;}
EditText.setText(Integer.toString(x));
}
});
ButtonCommit.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
txt.setText(Integer.toString(x));
editor.putInt("Value", x);
}
});
}
}