3

I have a very simple app that creates a text file (after a button click) and sends it to a certain email address(after another button click). I want to add the ability to change the name of the text file that is created based on how many times the file was sent, or i.e. how many times the app successfully ran till the end. Currently, the name of the text file is fixed.

My idea:

I am thinking of adding a check on start-up of the app to see if another text file exists, lets called it Counter.txt. This will contain the number of times the 'send' button was clicked. If the file doesn't exist, then it will create it and append the number 0. Every time the 'send' button is clicked, it will open Counter.txt and increment that number. Also on a 'send' click, it will email the main textfile that I want to send and adjust the name by appending the number from Counter.txt to it.

I am not sure if this is the best or most efficient method, so would appreciate other suggestions to achieve this. Thanks.

Community
  • 1
  • 1
user3451660
  • 447
  • 8
  • 17

2 Answers2

1

Why not use SharedPreferences to store the number of times the app was launched and increment the value on the onCreate() method of your main Activity?

Then when the mail is sent, the file is renamed based on the SharedPreferences value. I think it's better than changing the file name each time the app is started.

Here is a good Stack Overflow post on how to use SharedPreferences, you should check it out! There is also another post on how to rename a file here.

Hope this helps!

Neïl Rahmouni
  • 326
  • 2
  • 10
1

If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs. ~ Android Developer Documentation

// Create your shared preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

// Write to shared preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("yourkey", yourvalue); // You could store the counter right here
editor.commit();

// Read from shared preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = 0;
int lastcounter = sharedPref.getInt("yourkey", defaultValue);
finngu
  • 457
  • 4
  • 23