1

I have made an application. It's a button that shows the time you have pressed it. Every time I "kill" the application, the timer starts at 0 again (naturally). How can I make the application save the time the button is pressed, so when the application is killed, and then you open it, the timer is at that time you stopped.I have red some about how this is done, and I think it has something to do with SharedPreferences.

My code:

public class MainActivity extends ActionBarActivity {

    Button button1;
    Chronometer chromo;
    protected long time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button1=(Button)findViewById(R.id.button1);
        chromo=(Chronometer)findViewById(R.id.chromo);

        button1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if(event.getAction() == MotionEvent.ACTION_DOWN){
                    chromo.setBase(SystemClock.elapsedRealtime()+time);
                    chromo.start();
                }
                else if( event.getAction() == MotionEvent.ACTION_UP){
                    time =chromo.getBase()-SystemClock.elapsedRealtime();
                    chromo.stop();
                }
                return true;
            }
    });
}}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Leitvoll
  • 53
  • 4
  • Not much, because i doesn't quite understand how this works, and thats why i had to ask :) Can you help me? – Leitvoll Jan 08 '15 at 13:35

3 Answers3

1

Saving in SharedPreferences :

SharedPreferences prefs= getSharedPreferences("prefs", Context.MODE_PRIVATE);
// We use an editor to insert values in SharedPreferences
Editor editor = prefs.edit(); 
// Saving the values
editor.putLong("myTime", time); 
// Committing the changes
editor.commit(); 

Retrieving saved values :

long savedValue = 0l;
SharedPreferences prefs= getSharedPreferences("prefs", Context.MODE_PRIVATE);

if (prefs.contains("hello")){
    savedValue = sharedpreferences.getLong("myTime", 0l));
}
2Dee
  • 8,609
  • 7
  • 42
  • 53
  • Im quite new with coding, so I don't know how to use therse codes you just gave me, and which codes to use. Can you help me and describe how I do this with my spesific code. – Leitvoll Jan 08 '15 at 14:00
  • If I understand correctly, you want to save a time when the activity is closed and retrieve it when it is open again ? In that case, you could override the onDestroy method in your Activity, save the time in SharedPreferences in that method and in onCreate, after getting a reference to your timer, set the time based on the value you retrieve from SharedPreferences. Is that clearer ? If not, please explain in details what you have trouble with so I can help you get through this ;) – 2Dee Jan 08 '15 at 14:04
  • Yes, thats exactly what i want! But i still dont undersnand how that works. Could you please code it to me, or just show me an example. You have my code and know exactly what i need help with :) – Leitvoll Jan 08 '15 at 14:52
  • I won't code it for you, because I usually charge for this :) On a more serious note, me coding for you won't help you much, it's the whole "give a man a fish or teach him how to fish" story. But I would direct you to the official tutorial about managing activity lifecycle, and with the code for sharedpreferences I provided you with, you should get there : http://developer.android.com/training/basics/activity-lifecycle/index.html I highly recommend going through the basic training on the official page about the common subjects. Never be scared to try samples and play with them ;) – 2Dee Jan 08 '15 at 15:06
1

EDIT :

public class MainActivity extends ActionBarActivity {

    Button button1;
    Chronometer chromo;
    protected long time = 0;
    private SharedPreferences prefs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button1=(Button)findViewById(R.id.button1);
        chromo=(Chronometer)findViewById(R.id.chromo);
        prefs = getSharedPreferences("prefs", Context.MODE_PRIVATE);
        long savedValue = prefs.getLong("my_chrono", 0);

        if(savedValue == 0)
            chromo.setBase(SystemClock.elapsedRealtime());
        else
            chromo.setBase(SystemClock.elapsedRealtime() + savedValue);

        button1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if(event.getAction() == MotionEvent.ACTION_DOWN){
                    chromo.start();
                }
                else if( event.getAction() == MotionEvent.ACTION_UP){
                    time =chromo.getBase()-SystemClock.elapsedRealtime();
                    chromo.stop();
                    prefs.edit().putLong("my_chrono", time).apply();
                }
                return true;
            }
    });
}}

============================================================================

To use the shared preferences, initialize this in you onCreate

SharedPreferences prefs = getSharedPreferences("the_package_of_your_app", Context.MODE_PRIVATE);

Then, try to get the saved value

int my_saved_value = prefs.getInt("the_package_of_your_app.my_int_1", 0);
if(my_saved_value != 0)
    //your value of your timer was saved, do what's needed with it
else
    //there was no value saved, or the timer was at 0

Now you have to save that value when needed (when the timer is stopped, or the application is closed)

prefs.edit().putInt("the_package_of_your_app.my_int_1", my_value).apply();
Tr4X
  • 309
  • 1
  • 8
  • Thanks for the answer. I explained what i want to do in the question. Could you try to code that for me? (Or just help me by telling me). I guess i need that: "To save a value (let's say a int)". Im quite new with coding. – Leitvoll Jan 08 '15 at 13:52
  • I've updated the code above, for what I think you will have to save your value in the onStop method and also following your chromo.stop() – Tr4X Jan 08 '15 at 14:03
  • Great. 1 question: What is, my_value, my_saved_value and my_int_1? :) – Leitvoll Jan 08 '15 at 14:06
  • my_saved_value is the value you will get back fromsharedPreferences, the one you saved my_value is the value you pass to the sharedPreferences to be saved (in your case should be the value of your chrono) my_int_1 is just a string to identify your value in the sharedPreferences, it's id if you prefer – Tr4X Jan 08 '15 at 14:10
  • Is this right?? http://gyazo.com/5daa9bf7e363b7e03f7be41713af3c0b And why do i get an error on putInt?? I'd appreciate an answer! – Leitvoll Jan 08 '15 at 22:03
  • You're trying to put your "chromo" variable (which is a Chronometer) as a int in the putInt method... You don't have to save the chronometer but its value – Tr4X Jan 09 '15 at 15:19
  • Note : after further research (what you should have done...), the elapsed time can be retrieved like this : long ellapsedMillis = SystemClock.elapsedRealTime() - chromo.getBase(); Of course since it's a long, you have to change the putInt/getInt in putLong/getLong – Tr4X Jan 09 '15 at 15:27
  • I've updated the code above, considering what you try to achieve and the info I gave to you – Tr4X Jan 09 '15 at 16:08
  • 1st: That you so much!! I made it work, it did save, and when i for example pressed the back button, the time saved. 2nd: You didnt put: chromo.setBase(SystemClock.elapsedRealtime()+time); (located under "ACTION_DOWN") in your code, without that, the time runs in the background and doesn't really stop. When i put it in the code somthing strange happends! The time saves after killing the app, but, when i press the button, the time dissepears ans starts on 00:00 again. Why does this happend?? Againg thank you very, very, very much! – Leitvoll Jan 09 '15 at 16:33
  • Im so cose to making it! Could you please help me ;) @Tr4X – Leitvoll Jan 10 '15 at 12:47
  • if you put your chromo.setBase in the ACTION_DOWN section, it means that it will set your chrono at that time every time the button is pressed, that's why I haven't put it in that section, but rather in the init of the app Be careful that ACTION_DOWN means the moment your finger touches the button, and ACTION_UP means the moment you remove your finger from the button – Tr4X Jan 10 '15 at 15:30
  • But.. Do you know how to fix this? Without: chromo.setBase(SystemClock.elapsedRealtime()+time); The app dowsn't work the way i want. @Tr4X And thanks for answering! – Leitvoll Jan 10 '15 at 16:44
  • I've tried a a lot.. Help please :) Just as you understand: without, chromo.setBase(SystemClock.elapsedRealtime()+time); the time runs in the background and never stops. When i add chromo.setBase(S.... to the code, the timer restarts as soon as i kill the app, opends it, then toutches the button. (When i open it the time is still there, for example 00:12. But when i toutch the button, the timer reset.) @Tr4X – Leitvoll Jan 11 '15 at 14:07
  • Help meeeeeeee xP @ Tr4X – Leitvoll Jan 11 '15 at 21:45
0

To elaborate on @2Dee's answer:

SharedPreferences prefs= getSharedPreferences("prefs", Context.MODE_PRIVATE);
// We use an editor to insert values in SharedPreferences
Editor editor = prefs.edit(); 
// Saving the values
editor.putLong("myTime", time); 
// Committing the changes
editor.commit(); 

can go into the

protected void onDestroy();

method. This method can be overloaded in an Activity to be called as the activity is destroyed (killed, closed, etc) so that any data may be saved (which is what you want to do).

Likewise,

SharedPreferences prefs= getSharedPreferences("prefs", Context.MODE_PRIVATE);
time = sharedpreferences.getLong("myTime", 0l);

can go into the

protected void onCreate(Bundle savedInstanceState);

method. This method is called when the activity is first created. This will set your time to the saved value (defaulting to 0 if there is none).

If for some reason these need to be called at different times (such as later or earlier in the Activity's lifecycle) you can read more about it here.

If you like this answer, please upvote 2Dee's answer as well. Some of the code is literally copy/pasted from there.

Happy Coding! Leave a comment if you have more questions.

Matt
  • 5,404
  • 3
  • 27
  • 39
  • Thanks for the help. But Tr4X made a code that worked for me (with minor porblems i try to fix now). Again thanks for the help! – Leitvoll Jan 09 '15 at 16:40