I'm creating a simple click counter android app, sound is played when a button is clicked and the count is also saved when leaving the count screen and then returning to it.
I have encountered a problem with the mute button. When I click it, it mutes the whole application rather than just that particular gui screen (activity).
First issue is that the mute button mutes the sound for the whole app, and I only need to mute for that activity.
Second issue is that when you click mute button and come out of the screen, then go back, then try to unmute - it does not unmute the sound.
Was thinking the resolution to this is that we take the mute button out of the SharedPreferences save instance state - if this is possible...
Here is my code so far, if you can guide me on how to achieve the above that would be great. Thanks.
public class wazeefa extends Activity {
//Count Button
TextView txtCount;
ImageView image;
Button btnCount;
Button wmute;
Button wreset;
public static int count = 0;
SharedPreferences app_preferences;
MediaPlayer mpButtonClick;
AudioManager audioManager;
public static boolean mutestatus = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
setContentView(R.layout.wazeefa);
audioManager =
(AudioManager) getSystemService(Context.AUDIO_SERVICE);
//SAVE COUNT
app_preferences = this.getSharedPreferences("myPrefscount", MODE_WORLD_READABLE);
count = app_preferences.getInt("count", 0);
txtCount = (TextView) findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
image = (ImageView) findViewById(R.id.imageview);
txtCount = (TextView) findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
//Button SOUND AND COUNT
mpButtonClick = MediaPlayer.create(this, R.raw.bubble);
//RESET Button
wreset = (Button) findViewById(R.id.wreset);
txtCount = (TextView) findViewById(R.id.wcount);
txtCount.setText(String.valueOf(count));
btnCount = (Button) findViewById(R.id.wclick);
wmute = (Button) findViewById(R.id.wmute);
btnCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count++;
if (count > 50) count = 0;
image.setImageResource(R.drawable.duroodimage);
if (count > 0) image.setImageResource(R.drawable.duroodimage);
if (count > 9) image.setImageResource(R.drawable.zikrimage);
if (count > 39) image.setImageResource(R.drawable.duroodimage);
txtCount.setText(String.valueOf(count));
mpButtonClick.start();
}
});
wreset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count = 0;
image.setImageResource(R.drawable.duroodimage);
;
txtCount.setText("0");
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
});
wmute.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mutestatus) {
mutestatus = true;
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);
Log.v("'test....", "" + mutestatus);
} else {
mutestatus = false;
audioManager.setMode(AudioManager.MODE_NORMAL);
audioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, false);
Log.v("'test....", "" + mutestatus);
}
}
});
}
#Override
protected void onPause() {
super.onPause();
// save count value here
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
}
You are saving the preferences on the application level, make it Activity specific, i.e. Implement mute functionality for the activity not the application.
Edit
See your objective is some what to mute and unmute (loquent) the audio, Preferences can be saved in three ways.
1) Preferences can be retrieved only by a single activity.
2 )Preferences can be shared and retrieved among all activities within the application.
3)Preferences can be shared and retrieved through all applications on the device.
In your case, Saving Activity-level preferences:
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
editor.putString("pref 1", "some text");
editor.commit();
We get a SharedPreferences object by calling getPreferences(int mode) method which takes an integer value as a parameter, the mode value can be one of the following:
Context.MODE_PRIVATE (0): a file creating mode that makes the created file only accessible by applications with the same user ID (access the file from the same application context, will desctribe later).
Context.MODE_WORLD_READABLE (1): file mode makes the file readable from other applications.
Context.MODE_WORLD_WRITEABLE (2): file mode allows other applications to write to the file.
Then we get an instance of SharedPreferences.Editor and write the preference value with editor.putString(String key, String value) method.
shared preferences allows you to insert preferences using the following methods:
editor.putBoolean(String key, boolean value).
editor.putFloat(String key,float value).
editor.putInt(String key, int value).
editor.putLong(String key, long value)
editor.putString(String key, String value)
Then we call edit.commit() to save the preferences to the file. commit returns a boolean indicating the result of saving, true if successful and false if failed.
Reading preferences values:
To read preferences values:
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
String val=prefs.getString("pref 1", "some text");
We use sharedpreferences.getString(String key, String defaultValue) (or get boolean/float/int) to return the value stored with a specific key or defaultValue if not found.
Source
Related
Summary of problem: When I force close the app by opening task window and swiping it closed my if/else statement is not working properly. I have the Name Selection Activity as the Default Launcher Activity. The name selection Activity should only pop up if there are no Shared Prefs, meaning the user has not selected a name yet from the spinner. But even after the user has selected a name and it is stored in Share Prefs, when I force close the app I still get returned to the name selection activity
What I have tried I have tried if (stringNamePackage.equals("")) and if (stringNamePackage == "") and if (NAME.equals("")) and if (NAME == "") At first I thought it was because maybe my Shared Prefs was not saving the name correctly but it is not that, the name still appears correctly when I force close it. But when I try to add the if/else statment it always just sends me back to the name selection activity regardless if I have a name saved in Shared Prefs or not. I have spent 4 hours trying to get this to work and I am at my wits end. I also spent hours looking at different stack articles of how to save and retrieve Shared Pref data. I even tried how to check the SharedPreferences string is empty or null *android and it is still not working.
NameSelectionActivity
public class NameSelection extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner nameSpinner;
String stringNamePackage;
Button bSaveSelection;
Context context;
public ArrayAdapter<CharSequence> adapter;
public static String SHARED_PREFS = "sharedPrefs";
public static String NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_selection);
context = this;
nameSpinner = findViewById(R.id.horizonNameSpinner);
stringNamePackage = "";
//Create the list to populate the spinner
List<String> nameList = new ArrayList<>();
nameList.add("01");
nameList.add("02");
nameList.add("03");
//Array Adapter for creating list
//adapter = ArrayAdapter.createFromResource(this, R.array., android.R.layout.simple_spinner_item);
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, nameList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
nameSpinner.setAdapter(adapter);
nameSpinner.setOnItemSelectedListener(this);
//If User has not selected name, start this activity to allow user to pick Name, else, send user to Main Activity
//else start MainActivity
if (stringNamePackage .equals("")) {
Toast.makeText(this, "Welcome, please select Name", Toast.LENGTH_LONG).show();
} else {
Intent sendToMainActIntent = new Intent(this, MainActivity.class);
startActivity(sendToMainActIntent);
}
//Save Selection Button Code
bSaveSelection = findViewById(R.id.bSaveSelection);
bSaveSelection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), MainActivity.class);
//Saves name to SharedPrefs
saveName();
//Sends user to MainActivity
startActivity(myIntent);
finish();
}
});
}
//Stores name selected in SharedPreferences
public void saveName() {
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = app_preferences.edit();
editor.clear();
//Stores selection in stringNamePackage
editor.putString(NAME, stringNamePackage );
editor.commit();
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//Put user selection into String text
String text = adapterView.getItemAtPosition(i).toString();
stringNamePackage = text;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
Main Activity
The purpose of this activity case is to send the user back to the name Selection screen when they hit the "Test" button which will erase the shared prefs and hence, trigger the if/else statement and making the user pick a name. This is how I get and set the Name in Main Activity:
in onCreate
Getting name
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(context);
nameSharedPref = app_preferences.getString(NAME, "");
name.setText(nameSharedPref);
Clearing Name
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = mPrefs.edit();
editor.clear();
editor.commit();
finish();
What I expect: I expect the user to have to pick a name the first time they boot up the app. Then, every time they open the app an if/else statement will check if the user has a name or not in Shared Prefs. If they have a name they will go directly to the Main Activity. If they don't then they will go back to the Name Selection Activity.
To get data and store data to your SharedPreferences you use this:
SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
PreferenceManager.getDefaultSharedPreferences(context) is used to build "Settings" screens or similar, the first one you use it to store/retrieve arbitrary data not necessarily binded to UI.
Even more if you want to organize your SharedPreferences you could append to getPackageName() different keys like:
getSharedPreferences(getPackageName() + ".booleans", Context.MODE_PRIVATE);
getSharedPreferences(getPackageName() + ".flags", Context.MODE_PRIVATE);
getSharedPreferences(getPackageName() + ".keys", Context.MODE_PRIVATE);
each one of them is different file that stores shared preferences, you can ommit the prepending dot ., but for naming consistency it'll be better to keep it, there is no really need for the extra keys, but if you have some sort of OCD, that might be "relaxing" ;-).
Then you can use your Android Studio's Device Explorer to browse the shared preferences, they are located under "data/data/your.package.name/shared_prefs"
I want create content application, i load data from JSON and when users click on button save this content into SQLitedatabase.
I want use this library for button.
And for checkable button, I use this code
I write below codes, when click on button i save this content into SQLitedatabase, but i can't save button sate into SharedPreferences!
When click on button (boolean checked) button is turn on, and when click again on the button turn off this button.
I want when click on button, turn on this button and save in SharedPreferences and when go to other activity and again back this activity, see turn on this button NOT turn off. when click again this button at that time turn off button!
Activity codes:
private ShineButton postShow_favPost;
private String favData = "FavPrefsList";
private Boolean favState;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_show_page);
bindActivity();
//Give Data
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
title = bundle.getString("title");
image = bundle.getString("image");
content = bundle.getString("content");
dateTime = bundle.getString("dateTime");
author = bundle.getString("author");
category = bundle.getString("category");
categoryID = bundle.getString("categoryID");
}
mAppBarLayout.addOnOffsetChangedListener(this);
//// Save Fav state
final SharedPreferences saveFavPrefs = getSharedPreferences(favData, MODE_PRIVATE);
final SharedPreferences.Editor editor = saveFavPrefs.edit();
favState = saveFavPrefs.getBoolean("isChecked", false);
postShow_favPost = (ShineButton) mToolbar.findViewById(R.id.post_FavImage);
postShow_favPost.init(this);
postShow_favPost.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(View view, boolean checked) {
if (checked == true) {
editor.putBoolean("isChecked", true);
editor.commit();
//////////// Database
favDB = new FavHelper(context);
long addNewFAV = favDB.insertFAV(title, image, content, dateTime, author, category);
if (addNewFAV < 0) {
TastyToast.makeText(context, "Not save in database", TastyToast.LENGTH_LONG, TastyToast.ERROR);
} else {
TastyToast.makeText(context, "Save in database", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
}
////////////////////
} else {
editor.putBoolean("isChecked", false);
editor.commit();
Toast.makeText(context, "Checked False", Toast.LENGTH_SHORT).show();
}
}
});
How can i fix my issue ?
Well you need to save the state when you click the button.
For example :
postShow_favPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (postShow_favPost.isChecked()){
editor.putBoolean("isChecked", true);
editor.apply();
}
else{
editor.putBoolean("isChecked", false);
editor.apply();
}
}
});
Then you have to load it in your onCreate():
#Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences saveFavPrefs = getSharedPreferences(favData, MODE_PRIVATE);;
postShow_favPost.setChecked(saveFavPrefs.getBoolean("isChecked", true));
}
Maybe this example will help you.
EDIT
Ok let's presume in your f function you just finished doing whatever you're doing to your database, after that, set the state as on or off, let's say you want on.
So :
public void loadPrefs(SharedPreferences prefs){
favState = prefs.getBoolean("isChecked",false);
}
public void f(SharedPreferences.Editor editor){
//database stuff
editor.putBoolean("isChecked", true); // or false
editor.apply();
loadPrefs(prefs);
// in here your state will be saved for your button as soon as you
finish working with your database, after that in your onResume() you
may change that state to false(off) in case you want it just for that post
}
I am just trying to store the users input from an editText in a Shared Preference, but it is not working:
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
Log.v(TAG, keyword.getString("keyword", "mDefault")); //IT LOGS OUT THE DEFAULT STRING EVEN **AFTER** STORING THE PREFERENCES BEFORE
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
keywordEditor.putString("keyword", editText.getText().toString());
keywordEditor.commit();
Log.v(TAG, keyword.getString("keyword", "default")); //CORRECT! THIS LINE WORKS
}
}
return true;
});
When I first edit the text, I will first get a log of "mDefault" which is normal, since nothing is stored in the shared preference.
Then, I store something in the shared preference, and to make sure it stored, I log and I get a log of what I typed. Which means the shared preference data WAS stored.
Heres the problem: After I have stored something in the shared preference, I go to a different activity, and I come back, and all the data stored in the shared preference is GONE!
The very first log still says mDefault after navigating through activities.
What could the problem be?
EDIT:
Here is my instantiation:
onCreate:
keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences
keywordEditor = keyword.edit();
Maybe you don't save on setOnEditorActionListener. Save when you go to a different activity. Because when it goes to different activity the setOnEditorActionListener editText.getText().toString() it returns null.
STORING PREFERENCES:
SharedPreferences pref = getSharedPreferences("MyPrefs",Context.MODE_PRIVATE);
// We need an editor object to make changes
SharedPreferences.Editor edit = pref.edit();
// Set/Store data
edit.putString("username", "Rishabh");
edit.putString("password", "rishabh123");
// Commit the changes
edit.commit();
RETRIEVING PREFERENCES:
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String username = pref.getString("username", "");
String password= pref.getString("password", "");
Log.d(TAG, username);
Log.d(TAG, password);
Adding this as an example in case you missed a key components. This is currently working for me:
public class Main2Activity extends ActionBarActivity {
private SharedPreferences keyword;
private SharedPreferences.Editor keywordEditor;
private String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences
keywordEditor = keyword.edit();
final EditText editText = (EditText) findViewById(R.id.et_text);
findViewById(R.id.btn_launch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main2Activity.this, Main22Activity.class);
startActivity(intent);
}
});
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
Log.v(TAG, "Initial: " + keyword.getString("keyword", "mDefault")); //IT LOGS OUT THE DEFAULT STRING EVEN **AFTER** STORING THE PREFERENCES BEFORE
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
keywordEditor.putString("keyword", editText.getText().toString());
keywordEditor.commit();
Log.v(TAG, "Saving in prefs: " + keyword.getString("keyword", "default")); //CORRECT! THIS LINE WORKS
}
return true;
}
});
}
}
From a fresh install:
I typed in "test" and hit the send button on keyboard therefore invoked the onEditorAction
Then clicked on launch new activity -> hit back button and typed in "test2" and hit send button.
The following is the log out put:
02-29 23:26:42.068 18105-18105/com.example.naveed.myapplication V/TAG: Initial: mDefault
02-29 23:26:42.136 18105-18105/com.example.naveed.myapplication V/TAG: Saving in prefs: test
02-29 23:26:53.281 18105-18105/com.example.naveed.myapplication V/TAG: Initial: test
02-29 23:26:53.338 18105-18105/com.example.naveed.myapplication V/TAG: Saving in prefs: test2
As you can see initially it was "mDefault" then "test" was saved. I launched a new activity and came back. Next time the initial was "test" since it was saved last time and "test2" was the new value saved.
Create SharedPreferences class
public class SharedPreferenceClass
{
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "INTELLIJ_AMIYO";
public static final String KEY_SET_VALUE= "KEY_SET_VALUE";
public SharedPreferenceClass(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
}
public void setUserDATA(String data)
{
editor.remove(KEY_SET_VALUE);
editor.putString(KEY_SET_VALUE, data);
editor.commit();
}
public String getUserDATA()
{
String getData= pref.getString(KEY_SET_VALUE, null);
return getData;
}
}
Now call this in your Activity section globally
SharedPreferenceClass sharedPrefClassObj;
& call onCreate(Bundle savedInstanceState) section
sharedPrefClassObj = new SharedPreferenceClass(getApplicationContext());
Now add this
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
sharedPrefClassObj.setUserDATA(editText.getText().toString()); // Set data
// Get data sharedPrefClassObj.getUserDATA();
}
}
return true;
});
Very important: you need a Preference name (for example: "MY_PREFS_NAME") to set and retrieve the values:
SharedPreferences.Editor keywordEditor = context.getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).edit();
Use the same constant Preference name and it will give you the same preferences in any point of your app.
I am trying to make it possible that you can save a high score and I also need the user to be able to reset/delete their high score. the TOAST works but the data doesn't get deleted.
public static final String PREFS_NAME = "MyPrefsFile";
static SharedPreferences settings;
static SharedPreferences.Editor editor;
// When 'back' button is pressed save the highscore to settings
editor = settings.edit();// Create a new editor
editor.putInt("highscore", HighScore); // Storing integer
editor.commit();
// When 'Show' button is pressed
public void showPreferences(View v) {
int highscore = GameActivity.settings.getInt("highscore", GameActivity.HighScore);
Toast.makeText( MainMenu.this, "Your Highscore is: " + highscore, Toast.LENGTH_LONG).show();
}
//When delete button is pressed
public void clearPreferences(View V) {
GameActivity.editor = GameActivity.settings.edit();// Create a new editor
GameActivity.editor.clear();
GameActivity.editor.commit();
Toast.makeText( MainMenu.this,"Highscore has been reset",Toast.LENGTH_LONG).show();
}
I believe you are just reading it wrong, use this
int highscore = GameActivity.settings.getInt("highscore", 0);
Note that second parameter is the default value, a value that is returned if the value by that key is not present in the settings.
You can try this:
settings = getSharedPreferences("MyPrefsFile", 0);
preferences.edit().remove("highscore").commit();
Or you can update the sharepreference by the value 0.
Use the below to clear shared preferences
settings.edit().clear().commit();
Or use the below to clear single value from preferences
settings.edit().remove("highscore").commit();
I have multiple on click listeners implemented in the code. But, I want each click from seperate images to be saved in a "ticker" in shared preferences. So, if there are 2 clicks on image 1, 4 clicks on image 2, and 6 clicks on image 3, it totals up to be 12 "clicks" counted in shared prefs. The problem is, every onClickListener seems to overwrite the other, instead of stacking. Any ideas on how to accomplish this?
Image1.setOnClickListener(new View.OnClickListener() {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
int numClicks = pref.getInt("Total_Clicks", 0);
#Override
public void onClick (View v) {
numClicks++;
}
SharedPreferences pref =
getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Editor ed = pref.edit();
ed.putInt("Total_Clicks", numClicks);
ed.apply();
}
});
Image2.setOnClickListener(new View.OnClickListener() {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
int numClicks = pref.getInt("Total_Clicks", 0);
#Override
public void onClick (View w) {
numClicks++;
}
SharedPreferences pref =
getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Editor ed = pref.edit();
ed.putInt("Total_Clicks", numClicks);
ed.apply();
}
});
Image3.setOnClickListener(new View.OnClickListener() {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
int numClicks = pref.getInt("Total_Clicks", 0);
#Override
public void onClick (View x) {
numClicks++;
}
SharedPreferences pref =
getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Editor ed = pref.edit();
ed.putInt("Total_Clicks", numClicks);
ed.apply();
}
});
You are keeping track of the numclicks 3 times (inside each OnClickListener), so it makes sense for them to override each other.
For starters you could create your OnClickListener only once, and assign it to each image. This should solve it:
View.OnClickListener imageClickedListener = new View.OnClickListener() {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
int numClicks = pref.getInt("Total_Clicks", 0);
#Override
public void onClick (View v) {
numClicks++;
Editor ed = pref.edit();
ed.putInt("Total_Clicks", numClicks);
ed.apply();
}
}
Image1.setOnClickListener(imageClickedListener);
Image2.setOnClickListener(imageClickedListener);
Image3.setOnClickListener(imageClickedListener);
EDIT:
I've added a reply to your comment here cause I find it clearer.
The sharedPreferences instances were not the problem. They all talk to the same saved data ("ActivityPREF"). The problem was that you had 3 instances of OnClickListener, and all 3 of them were holding the integer numClicks. So they all started at 0 (or previously saved amount), and only increased the local numClicks. So if I tapped image1 twice, the numClicks inside that listener would be on 2. While the other ones would still be at 0.
It would have worked if you would have added the following to the onClick methods, before increasing the numClicks:
numClicks = pref.getInt("Total_Clicks", 0);
Since it would then reload it from the saved value. Only the code inside the onClick method is called each time a click is made, not the code you add when instantiating an OnClickListener.