0

I am trying to display a dialog based on the number of clicks that have occurred. I have two little issues with it which I will explain below:

So I clear the data on my app so that the number of clicks starts on 0. Basically what I am trying to do is that when I access the class below, if the number of clicks = 4, 8 or 12, then output the relevant message associated to them in my if else statements. If it doesn't equal any of those numbers then for every 4 clicks (16, 20, 24 ,28 etc) display the default message of 'You are rewarded with a video.

So starting from fresh on zero clicks, when I navigate to this page I notice for each click (1,2,3,4 etc) it displays the default dialog message which is not what I require. I want it to display the messages for 4, 8, 12 which have their own specific messages and then there after (16, 20, 24, 28 etc) should display the general message.

What I have also noticed is that if I come out of the page by selecting the back button and then access the page again, every time the dialog appears it takes me many taps on the ok button for the dialog to close. Initially before I went back from the page it only took me one tap to close the dialog but when I re-enter the page then it takes many taps and I am not sure why.

How can these 2 issues be fixed?

Code below:

import java.util.Random;

public class Content extends AppCompatActivity {

Button backButton;
Button selectAnotherButton;
TextView clickCountText;
int getClickCountInt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_content);


    final SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(Content.this);
    clickCountText = findViewById(R.id.click_count);
    clickCountText.setText(Integer.toString(prefManager.getClicks()));
    getClickCountInt = Integer.parseInt(clickCountText.getText().toString());

    backButton = findViewById(R.id.button_back);
    selectAnotherButton = findViewById(R.id.button_select_another);

    setContent();

    selectAnotherButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));

            if (getClickCountInt == 4){
                ShowRewardDialog("You are rewarded with a the yellow smiley face in the homepage");
            } else if (getClickCountInt == 8) {
                ShowRewardDialog("You are rewarded with a the green smiley face in the homepage");
             } else if (getClickCountInt == 12) {
                ShowRewardDialog("You are rewarded with a the red smiley face in the homepage");
             } else {
                for(int i = 0; i <= getClickCountInt; i+=4) {
                ShowRewardDialog("You are rewarded with a video\"");
                }
            }

            setContent();
        }
    });

    backButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}


private void ShowRewardDialog(String message) {

    final Dialog dialog = new Dialog(Content.this);
    dialog.setContentView(R.layout.custom_dialog);

    SpannableString title = new SpannableString("YOU GAINED A REWARD");

    title.setSpan(new ForegroundColorSpan(Content.this.getResources().getColor(R.color.purple))
            , 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    // set the custom dialog components - text, image and button
    TextView text = dialog.findViewById(R.id.dialog_text);
    dialog.setTitle(title);

    text.setText(message);

    Button dialogButton = dialog.findViewById(R.id.dialog_button_OK);
    // if button is clicked, close the custom dialog
    dialogButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    dialog.show();
  }
}

UPDATE

Ok to make it easier I will say what is the current problem and how I want it to work.

I have disabled the else statement for now in the Content class where it displays a generic message in the dialog box.

Ok so I have created a class for my Shared Preferences and I can get an instance of it from both the MainActivity class (this is my homepage) and Content class (this is second page).

Lets say the click counts starts on 0 (and I display this as a text) and I am on the homepage. When I select the jokes button from the homepage, I will navigate to the second page and the count starts at 1. If I select 'Select Another' button which is displayed in second page, then the count goes to 2 (as I can see by the text displayed), click again then three and click again it will go to 4 and the dialog box for count 4 is displayed. This works for when I go to 8 and 12 as well.

When I select the 'Back' button to go from second page to front page, I can see the count remains the same as the count displayed in the second page. E.g if count was set to 8 on page 2 and I click back, the homepage displays the count of 8 as well when I view the text.

This seems all well and good. However lets start again from 0. If I click on the jokes button then I am on 1, I select 'Select Another' button twice so the count is on 3 and then click back button. Count is currently on 3 when I view the homepage. If I click on the jokes button again then the count is on 4 which is correct, however the dialog for if count equals to 4 does not appear. However if I click on the 'Select Another' button 3 more times then it will display the dialog for 4. So it seems like the dialog will only appear for 4 if the 'Select Another' button is clicked four in a row, rather than how I want it which is if the total number of clicks count equals 4 then show the dialog.

What will I need to do to fix this?

Below is the code:

SharedPreferencesManager class:

public class SharedPreferencesManager{

    private static final String APP_PREFS = "AppPrefsFile";
    private static final String NUMBER_OF_CLICKS = "numberOfClicks";

    private SharedPreferences sharedPrefs;
    private static SharedPreferencesManager instance;



    private SharedPreferencesManager(Context context) {
        sharedPrefs = context.getApplicationContext().getSharedPreferences(APP_PREFS, MODE_PRIVATE);
    }


    public static synchronized SharedPreferencesManager getInstance(Context context){
        if(instance == null)
            instance = new SharedPreferencesManager(context);

        return instance;
    }

    public int increaseClickCount() {
        int clickCount = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
        clickCount++;
        SharedPreferences.Editor editor = sharedPrefs.edit();
        editor.putInt(NUMBER_OF_CLICKS, clickCount);
        editor.apply();
        return clickCount;
    }

    public int getClicks(){
        return sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
    }
}

MainActivity class (page 1)

public class MainActivity extends AppCompatActivity {



       SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(this);

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            Button jokesButton = findViewById(R.id.button_jokes);;

            jokesButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    prefManager.increaseClickCount();
                    openContentPage("jokes");
                }
            });


            TextView clickCountText = findViewById(R.id.click_count);
            clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));


        }

        private void openContentPage(String v) {
            Intent intentContentPage = new Intent(MainActivity.this, Content.class);
            intentContentPage.putExtra("keyPage", v);
            startActivity(intentContentPage);

        }


    }

Content class (page 2):

public class Content extends AppCompatActivity {

Button backButton;
Button selectAnotherButton;
TextView clickCountText;
int getClickCountInt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_content);


    final SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(Content.this);
    clickCountText = findViewById(R.id.click_count);
    clickCountText.setText(Integer.toString(prefManager.getClicks()));
    getClickCountInt = Integer.parseInt(clickCountText.getText().toString());

    backButton = findViewById(R.id.button_back);
    selectAnotherButton = findViewById(R.id.button_select_another);

    setContent();

    selectAnotherButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getClickCountInt++;
            clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));

            if (getClickCountInt == 4){
                ShowRewardDialog("You are rewarded with a the yellow smiley face in the homepage");
            } else if (getClickCountInt == 8) {
                ShowRewardDialog("You are rewarded with a the green smiley face in the homepage");
             } else if (getClickCountInt == 12) {
                ShowRewardDialog("You are rewarded with a the red smiley face in the homepage");
             } //else {
                //for(int i = 0; i <= getClickCountInt; i+=4) {
                //ShowRewardDialog("You are rewarded with a video\"");
                //}
            //}
        }
    });

    backButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}


private void ShowRewardDialog(String message) {

    final Dialog dialog = new Dialog(Content.this);
    dialog.setContentView(R.layout.custom_dialog);

    SpannableString title = new SpannableString("YOU GAINED A REWARD");

    title.setSpan(new ForegroundColorSpan(Content.this.getResources().getColor(R.color.purple))
            , 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    // set the custom dialog components - text, image and button
    TextView text = dialog.findViewById(R.id.dialog_text);
    dialog.setTitle(title);

    text.setText(message);

    Button dialogButton = dialog.findViewById(R.id.dialog_button_OK);
    // if button is clicked, close the custom dialog
    dialogButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    dialog.show();
  }
}
Pristin
  • 175
  • 1
  • 2
  • 13

1 Answers1

0

The first problem with your algorithm is that you're not adding the current clicks to your click count. Inside the onClick of selectAnotherButton.setOnClickListener you should add a getClickCountInt++ (and dont forget to update clickCountText with this new value).

Also, on your onCreate you should get the value for getClickCountInt from SharedPreferences, and then use it to set the value on clickCountText, not the other way around.

This answear shows how to read/store data in SharedPreferences.

ViniciusMS
  • 56
  • 6
  • Ok, I will try, is it ok if you can post a coding example so if I don't get anyway I can see how to implement it they way you stated please? I think it's the final part on saving it that I might need to see as I am still learning how shared preferences work – Pristin Jun 15 '18 at 14:37
  • Yeah I will need a coding example as unable to get it working – Pristin Jun 15 '18 at 15:01
  • Hey there! I just updated my answear with a link to another answear on how to deal with SharedPreferences. Let me know if you have any trouble with it! You should also check it to see how to properly retrieve your data besides storing it. – ViniciusMS Jun 15 '18 at 15:04
  • Ok, I nearly have got it but I think I need you help because I am stuck on saving it from the second class. I place an update of my code in the question but basically I have stored all shared preferences in to own class and retrieve it from main active and able to retrieve it from content class. I'll explain what's happening though. Give me 15 mins to write it up – Pristin Jun 15 '18 at 15:18
  • Ok I provided an updating explaining the issue currently. – Pristin Jun 15 '18 at 15:41