Save and open a TimerTime in the Preferences - java

I'm currently working on a small Android game. In the options menu you can select the time you wish to play, either 15, 30 or 45 seconds. I have a countdown timer that loads these values. Now on my onPause, I want to save the current time and then onResume proceed from that time.
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
int cTime = Integer.valueOf(sharedPrefs.getString("playTimePref", null));
TimerTime = cTime;
timer = new CountDownTimer(TimerTime, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("Seconds Remaining: " + millisUntilFinished/ 1000);
TimerTime = (int) millisUntilFinished;
}
protected void onPause() {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("playTimePref", "TimerTime");
timer.cancel();
}
I thought this would work. If I'm correct I save the current TimerTime in the playTimePref string at onPause, and open that on onResume. But everytime I recall the app, the time resets to its original time. Hope someone can help.

this method
final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
will create the shared preference with your package name (com.xxx.xxx) and will be accessible by all activities you have.
but this method
getPreferences(MODE_PRIVATE)
will create shared Preference with your activity name (MainActivity) and it will be accessible only with your activity because your assign private mode for it , so as you can see you try to save your data in sharedPref and try to access the values from another one , that's why it return null for you
another comment on your code , you can use save time of casting string to int by using strong type mehod
Editor.putInt("Key" , timenumber);
hope it help you

Related

How to store time in sharedpreferences across two activities

When my users play a game, I want to lock them out of it for 30 seconds. I'm trying to use SharedPreferences. I'm not well acquainted with SP and not completely sure how to use it. So it should look like so
ifGameOver(){
//lock the game for 30 seconds
//send users to main menu until 30seconds is over
}
and then at the main menu I wish to be able to see a TextView count down as the 30 seconds go down. So here I would getLong or something(?). Could anyone shed any light on this?
Save current time to SharedPreferences in first Activity class:
private void saveCurrentTIme() {
SharedPreferences sharedpreferences = getSharedPreferences("myAppPref",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putLong("GameTime", System.currentTimeMillis());
editor.commit();
}
Retrieve saved time from SharedPreferences in second Activity class:
private long getSavedTime() {
SharedPreferences sharedpreferences = getSharedPreferences("myAppPref", Context.MODE_PRIVATE);
return sharedpreferences.getLong(Name, 0L);
}
For comparing if the saved time is passed, you can create something like Timer.
You can check this answer for how to do it.

How to reset CountDownTimer without having to pause first

Novice looking for some help~
I have a CountDownTimer with start, pause, and reset buttons. When the timer is running, I'd like to be able to hit the reset button to restart it from the original value (edittext.) Currently, the only way I am able to accomplish this is to hit "pause" then "reset."
To give an example of what I'm hoping to accomplish:
If timer is set to 10s,
10-9-8-reset-10-9-8-7-6-5-reset-10-9....
Thanks in advance!
I've looked through the forums and android dev site
EDIT: Original problem solved but another has arisen. Code below shows changes made. If I hit start-pause-start too quickly, one second is added to the original countdown time. For example: 15-14-pause-start-15-pause-start-16-pause-start-17-pause-start-18
private void pauseTimer(boolean actualPause) {
mCountdowntimer.cancel();
mTimerRunning = false;
if(actualPause)
updateWatchInterface();
}
private void resetTimer() {
if(mTimerRunning)
pauseTimer(false);
mTimeLeftInMillis = mStartTimeInMillis;
updateCountDownText();
updateWatchInterface();
}
I am not sure what your exact problem is, so I will mention a couple of approaches.
Option 1: If you don't have any problems remembering the 'start time' (that's what mStartTimeInMillis denotes, right?), then you can simply change the signature of the function pauseTimer as follows:
private void pauseTimer(boolean actualPause) {
mCountdowntimer.cancel();
mTimerRunning = false;
if(actualPause)
updateWatchInterface();
}
private void resetTimer() {
if(mTimerRunning)
pauseTimer(false);
mTimeLeftInMillis = mStartTimeInMillis;
updateCountDownText();
updateWatchInterface();
}
Also modify the top portion as:
public void onClick(android.view.View view) {
if (mTimerRunning) {
pauseTimer(true);
}
//...Other code
}
This will ensure that the watch interface is not updated to show the paused interface when you press the reset button, but the actual working would be as if you had pressed pause first and then reset. Also, we put a check to ensure that the pause timer is not called if it was actually pause followed by reset.
Option 2: If you can't get the reference to mStartTimeInMillis without calling pause first, you can use SharedPreferences, and save the start time every time you start the timer, thus allowing you access to the variable as follows:
//Put
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("time", *Your_value* );
editor.apply();
//Get
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("time", "00:00");//"00:00" is the default value if the //entry doesn't exist.
I hope these will be helpful :)

How to keep the countDownTimer counts after i swap the activity?

i need a countDownTimer keep running when i swap between activities.. i have more than one activity, i put the countDownTimer in the main activity but when i swap to another activity and back to the main activity it turns back to count again from the start, i believe because the method countDownTimer is onCreate method.
So, how should I go about doing this?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questionTime();
}
public void updateTimer(int secondsLeft){
int minutes = (int) secondsLeft / 60;
int seconds = secondsLeft - minutes * 60;
String secondString = Integer.toString(seconds);
timerTextView.setText(Integer.toString(minutes) + ":" + secondString);
}
private void questionTime(){
new CountDownTimer(10000, 1000){
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
timerTextView.setText("0:00");
Log.i("finished", "timer Done");
}
}.start();
}
Update: That helped me to reach my purpose How to run CountDownTimer in a Service in Android?
Maybe this is a little far fetched, but the way that I think to solve this issue and not worrying for the Activities is using an IntentService.
Even if you store some sort of value in the Bundle of the onSaveInstance() hook method this can lead to some pretty messy results if you enable the "Don't keep activities" flag in the device's settings.
What I would do is create an IntentService that when It's triggered starts the countdown, then It broadcast the changes of that countdown through EventBus/Otto/BroadcastReceiver back to the UI.
Another way of doing it is having the countdown instance in your Application class, and check it from there.
I would go with the IntentService solution because having a countdown instance running in the Application class sounds a little off.
Let me know if you want any specifics on how to implement the IntentService but a little bit of Googling should show you how to do it.
As soon as the time starts, write the time (unix timestamp) to properties file. And when the user comes back to your main activity, read the properties file and compare it the time in the properties file with current timestamp and update the timer based on that.

How can i have my Android app resume where i left off

I have simple counter application where, whenever you click the button, a textview shows the number increasing. If you click the button 10 times, the textview shows 10. Then, when I exit from the app and launch the app again, the application restarts all the activities I have done previously.
How can I continue to count where I left off previously? For example, I want to open my app and count up to 8 with the counter. When I exit, and after re-launching the activity, I want to continue counting where I left off from 8.
Please take a look at the source code:
TextView tv4;
ImageButton button5;
int counter=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_ikinci);
tv4=(TextView)findViewById(R.id.textView4);
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
tv4.setText("" + counter);
}
});
On your activity's onStop() method try to save your data in SharedPreferences
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("key", count);
editor.commit();
And when you launch it, on your main Activity onCreate() method retrieve your SharedPreferences value by key and continue where you left off
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
int count = prefs.getInt("key",0); //0 is the default value.
If you need to store little pieces of data throughout your activity's lifecycle it should be enough to store your counter variable in a Bundle inside onSaveInstanceState (Bundle outState) method. Note - don't forget to call super of that method after putting your variable into the Bundle.
This particular Bundle is passed to two methods on recreating Activity: onRestoreInstanceState() and onCreate() methods. So you can reset you instance variable from there.
For more info look here: http://developer.android.com/training/basics/activity-lifecycle/recreating.html

Can we make element global in android

I am using
<Chronometer android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="#+id/chrono"
android:visibility="gone" />
in my one activity now my question is can I make it global for all of my activities so that I can show its value to every activity in my android app?
If yes then how to do this please give example because I am new in android??
Here is my timer code
Chronometer stopWatch;
stopWatch.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener(){
#Override
public void onChronometerTick(Chronometer arg0) {
countUp = (SystemClock.elapsedRealtime() - arg0.getBase()) / 1000;
long min = countUp / 60;
long sec = countUp % 60;
String minStr = "";
String secStr="";
if(min < 10)
{
minStr = "0"+min;
}
else
{
minStr = ""+min;
}
if(sec<10)
{
secStr = "0"+sec;
}
else
{
secStr = ""+sec;
}
// String asText = (countUp / 60) + ":" + (countUp % 60);
String asText = minStr + ":" + secStr;
textGoesHere.setText(asText);
}
});
stopWatch.start();
Here is an idea. Create a separate layout for your Chronometer and <include /> it in all the layouts that require a Chronometer.
Now you can either use a Singleton pattern or SharedPreferences to store the attributes such as start time, current state (Paused, Running, Stopped, Reset) of your timer. Whenever you start a new activity get the state of the timer and show it on your Timer.
For instance if the current state is running then you may have to kick start a thread to update the timer or if the timer is stopped just get the start time and stop time from your SharedPreference or your Singleton class and show it on the timer.
For instance, consider the following scenario. For simplicity let's have 2 Activities, ActivityA and ActivityB.
Now here are some of the states for your timer, yours could be different.
Ready (00:00 - Your timer is ready to run)
Running (Timer is running)
Paused (Timer is paused and can be resumed)
Stopped (You have stopped the timer and it displays the elapsed time and the next possible state would be 1 i.e, ready.)
You would need several other parameters such as,
Timer start time (System.currentTimeInMillis() minus this time gets you elapsed)
Timer stop time (Used to calculate timer paused and stopped time)
Let's consider this case. You are starting a timer from ActivityA and want to retain the state on ActivityB. Here are the set of things you might want to do.
When you start your timer by any event - say click of a button, you have to save the start time in your SharedPreference.
Now you want to navigate to ActivityB, then you have to save the timer state to your SharedPreference in the onStop() method of your ActivityA.
Now after you start ActivityB, in the onResume() method get the start time from the SharedPreference, the System.currentTimeInMillis() minus the start time will give you the elapsed time. Next, you have to get the timer state from your SharedPreference.
If the state is running, then you have to start a thread to update the timer. If the timer is stopped, then it's enough to show the time elapsed on your timer.
This is the outline of the solution. You can learn about SharedPreferences from here.
Also, you need to be familiar with the Activity lifecycle, which you can learn from here.
No, you can't.
Activities have a life cycle in Android : they are created, started, display & do stuff, get stopped and destroyed. And all the views inside obey to this life cycle.
Don't fight against it, that's the way Android is and it's great like that, learn this life cycle.
The views of an activity don't exist outside of it. This would have no meaning. You should read on how to pass information from one activity to another.
Also, maybe your question is : how can all my activities have the same view in their layout, each one having its own instance of the view. In that case, use the include xml keyword.
yes you can do this but not by making it global. it is little tricky.
what you have to do is:
- make choronometer xml declarartion with tag in each Activity.
- make access of this chronometer in base class.
Just like an example: i required header in each of activity but i wanted to do coding only at one place. so what i do is:
/**
* Method to init Header components sets header bar title and header bar
* buttons. This method sets onClickListener to
*/
private void initHeader() throws InvalidHeaderTitleException {
try {
View headerView = findViewById(R.id.header_layout);
if (headerView != null) {
headerTextView = (TextView) headerView
.findViewById(R.id.layout_header_textview_header);
nextHeaderButton = (Button) headerView
.findViewById(R.id.layout_header_button_next);
prevHeaderButton = (Button) headerView
.findViewById(R.id.layout_header_button_previous);
if (headerTextView != null) {
String title = getHeaderText();
if (isValidString(title)) {
if (title.length() > IDryIceUIConstants.LENGTH_HEADER_TEXT)
title = title.substring(0,
IDryIceUIConstants.LENGTH_HEADER_TEXT)
+ IDryIceUIConstants.SUFFIX_HEADER_TEXT;
headerTextView.setText(title);
} else {
throw new InvalidHeaderTitleException(title);
}
}
if (nextHeaderButton != null) {
nextHeaderButton.setVisibility(getVisibility());
nextHeaderButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
headerNextButtonClicked();
}
});
}
if (prevHeaderButton != null) {
prevHeaderButton.setVisibility(getVisibility());
prevHeaderButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
headerPrevButtonClicked();
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
xml declaration in each Activity xml is
<include
android:id="#+id/header_layout"
android:layout_width="fill_parent"
android:layout_height="40dip"
layout="#layout/layout_header" />

Categories