-1

In my application I have a counter that increases with the use of certain buttons. My problem is that I would like to save the state of the counter. When I close the application and reopen this resets, and I want to show the result that there was before closing the app

code:

TextView Display;
int counter = 0 ;



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


Display = (TextView)findViewById(R.id.counter);


Button example:

counter = counter-3;
Display.setText(""+counter);

1 Answers1

1

You have many ways to do that, depends on the application and its uses

You can

  1. Use shared preferences (preferred as per your question)

    refer to How to use SharedPreferences in Android to store, fetch and edit values

  2. Not a good practice but if you want you can save in a file.

  3. Use Sqlite (tons of tutorial, e.g. Android SQLite Database Tutorial)

Community
  • 1
  • 1
empr777
  • 91
  • 6
  • I could send the "number" from onPause and take that "number" to onResume. I know sharedPreferences but I do not know how to make it work for this – francescofalletta Apr 02 '14 at 17:43
  • Here add something like this //your key can be string --"counter" and value as counter SharedPreferences sp = context.getSharedPreferences(PREF_NAME, Activity.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString(key,value); editor.commit(); – empr777 Apr 02 '14 at 17:52