-1

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);

            }

        });


    }



}
Faris Kapo
  • 346
  • 9
  • 30

2 Answers2

1
public class MainActivity extends AppCompatActivity {

  private int x;   //declare here

Now in your onCreate()

    @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();


         x = pref.getInt("Value", 0);  //assign values to global variable
         //rest of the code
    }

See this for different Types of variables and Their usage

rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
0

declare x as a member field of your Actvity and it will be accessible in your inner class

Basil
  • 845
  • 9
  • 24