Search code examples
androidonclicklistenerpreferences

Saving number of button clicks to a preference


I am writing an android app and I would like to save the amount of times a user clicks a button in a preference and then retrieve that preference in another class. I am complete beginner at this point and any help would be appreciated.


Solution

  • Do this way..

    **Activity1.java**
    ------------------
    
    SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    int myIntValue = sp.getInt("your_int_key",0);
    
    
            yourbutton.setOnClickListener(new OnClickListener() {
    
                        @Override
                        public void onClick(View v) {
    
                        editor.putInt("your_int_key",++myIntValue);
                                    editor.commit();
                        }
                    });
    
    **Activity2.java**
    -----------------
    
      SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
     int myIntValue = sp.getInt("your_int_key", 0);