0

I want to make a simple android app to - generate sequential number every time a button is pressed and save it as it is when it is closed. So when I open it next time it starts from there.

In JAVA I got sequential number part figured. But don't know how to save that number upon closing the app.

Just a simple hint could help me find out the rest.

This is my first question here so ignore if you find it too childish.

Thanks!!

Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
  • 5
    Possible duplicate of [How to save data in an android app](https://stackoverflow.com/questions/10962344/how-to-save-data-in-an-android-app) – Arnaud Jun 15 '18 at 06:23
  • 1
    You could use one of the built in simple consistency features: `SharedPreferences` (https://developer.android.com/reference/android/content/SharedPreferences) – deHaar Jun 15 '18 at 06:23

2 Answers2

0

There are many ways to do it:

  1. Using saveInstanceState() and onRestoreInstanceState() these are the two android activity life cycle methods to store data at the time of closing your app.
  2. You can use SharedPreferences to save your data. It basically uses a small XML file for storing your data permanently.
  3. You can also use SQLite database for storing data. [But for this purpose it is not preferable.]

Hope it will meet your question.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
0

Use SharedPreference like -

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

        // Get your last saved sequential number
        num = getMyNumber();

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ++num;
                saveMyNumber(num);
            }
        });
       ......
     }

    private void saveMyNumber(int num) {
        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt("sequencialnum", num);
        editor.commit();
    }

    private int getMyNumber(){
        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        return sharedPref.getInt("sequencialnum", 0);
    }
Deven
  • 3,078
  • 1
  • 32
  • 34