Skip to content Skip to sidebar Skip to footer

Adding To Sharedpreference Value With Multiple Onclicklistener

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

Solution 1:

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.


Post a Comment for "Adding To Sharedpreference Value With Multiple Onclicklistener"