-1

When I'm leaving my app, my counter gets reset.

I know that I need to use the onPause and onResume functions. However, I don't know how to write it in the code.

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

        final Button b1 = findViewById(R.id.b1);

        eggcounter = 100;
        final ImageButton ImgButton = findViewById(R.id.eggBtn);

        ImgButton.setOnClickListener(
                new View.OnClickListener() {

                    public void onClick(View view) {
                        eggcounter = eggcounter - 1;
                        updateEgg();

                        if (eggcounter < 80) {

                            ImgButton.setImageResource(R.drawable.egg_2);

                            if (eggcounter <60){
                                ImgButton.setImageResource(R.drawable.egg_3);

                                if (eggcounter <40) {
                                    ImgButton.setImageResource(R.drawable.egg_4);
takendarkk
  • 3,347
  • 8
  • 25
  • 37
KinqNick
  • 19
  • 4
  • [Read the docs](https://developer.android.com/guide/components/activities/activity-lifecycle). – Matt Clark May 04 '19 at 21:55
  • 1
    Possible duplicate of [onPause() and onStop() in Activity](https://stackoverflow.com/questions/11387258/onpause-and-onstop-in-activity) – Matt Clark May 04 '19 at 21:56

1 Answers1

1

If you want to save your application state, you can use Shared Preferences. Example :

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

        // You can call to onResume() or on Pause() in onCreate();
        onResume();
        onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        // After receiving this call you will usually receive a following call 
        // to onStop() and return to your activity 's onResume()
    }

    @Override
    public void onPause() {
        super.onPause();
        // When you receive a call, your activity is going into the background 
        // (to onPause) but your activity can be killed to reclaim resources 
        // (if there are not enough resources to start the new activity)
    }

so if you want to save your instance application state, you can save to Shared Preferences, SQLite and so on. Call it in onPause() or onStop() and reclaim this data in onResume()