Counter restarts after killing app - java

I have made an app that starts a counter when I hold the button, and stops counting as soon as I release the button, then start again as soon as I touch it again.. (The app is made to see how long time I can use, to touch a button.)
Anyway, I have made a way to save the data of the counter, so when I kill the app or press the "back button", the data of the counter saves. BUT as soon as I tap the button again it restarts! I can't find a way to fix this. I think it has to do something with:
chromo.setBase(SystemClock.elapsedRealtime()+time);
(Found under "ACTION_DOWN") I've used chronometer as my counter by the way. Please help me!
Here's my code:
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.setBase(SystemClock.elapsedRealtime()+time);
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;
}
});
}}

Related

How To Use OnTouchListener To Open New Activity

I Tried OnClickListener an OnLongClickListener And yea it worked but those are too quick and i want to make them even more longer and i am just unable to use OntouchListener To Open New Activity And i have no clue almost tried everything nothing worked
Activity Name: Website
Button id: action_button (its a floatingActionbutton)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton actionButton = findViewById(R.id.action_button);
defineView();
handleIntent();
defineActionBar();
checkPermission();
//i tried both here
public void openWebsite() {
Intent intent = new Intent(this, Website.class);
startActivity(intent);
Not sure why you want to use OnTouchListener instead of OnClickListener since I don't think there is any difference between them referring to button events.
whit OnClickListener you could capture long press with:
button.setOnLongClickListener {
//ACTION
true
}
EDIT: (for custom duration, you should use OnTouchListener, thats right)
you can do something like this:
long time = 0;
button.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
time = System.currentTimeMillis();
}
else if(motionEvent.getAction() == MotionEvent.ACTION_UP){
double duration = (System.currentTimeMillis() - time / 1000.0);
if(duration > 5){
action2();
return true;
}else if(duration > 3.2){
action1();
return true;
}
}
return false;
}
});

How to change widget visibility from outside of OnCreate method? Java Android Studio

I have a seekbar that I want to disappear when I press a button, and reappear after a countdown. I have used seekBarTimeToPlay.setVisibility(view.INVISIBLE); in the onFinish() method after the countdown.
However, I get the error "cannot resolve symbol 'view'." And also "cannot resolve symbol 'seekBarTimeToPlay'." but seem to resolve this by adding another SeekBar seekBarTimeToPlay = (SeekBar) findViewById(R.id.seekBarTimeToPlay); inside the method.
//change timeToPlay seekBar
SeekBar seekBarTimeToPlay = (SeekBar) findViewById(R.id.seekBarTimeToPlay);
//set progress/thumb pos to right place
seekBarTimeToPlay.setProgress(timeToPlay);
seekBarTimeToPlay.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
timeToPlay = progress;
updateTimeToPlay(timeToPlay, false);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
updateTimeToPlay(timeToPlay, true);
}
});
//start playing, countdown
final Button buttonMain = (Button) findViewById(R.id.buttonMain);
buttonMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//countdown, updating time to tidy text view, progress bar or clock animation
SeekBar seekBarTimeToPlay = (SeekBar) findViewById(R.id.seekBarTimeToPlay);
if (phase == "none") { //parent presses button, child starts playing
phase = "playing";
buttonMainText = "Pack Away Now";
//hide seekBar, doesn't change layout
seekBarTimeToPlay.setVisibility(View.INVISIBLE);
startCountDown(timeToPlay);
} else if (phase == "playing") {//parent presses button to pack away before time ended
phase = "tidying";
buttonMainText = "Confirm tidied up";
countDownTimer.cancel(); //maybe error if countdown isn't running, if statement might solve
updateTimeToPlay(timeToTidy, false);
startCountDown(timeToTidy); //new 10 minute countdown to wait for conformation that toys are away
//waiting to receive conformation, if received cancel countdown n that
} else if (phase == "tidying") { //parent presses button confirming packed away
countDownTimer.cancel(); //maybe error if countdown isn't running, if statement might solve
phaseWasTidying();
}
buttonMain.setText(buttonMainText); //change text to whatever stage
//returns here after button pressed
seekBarTimeToPlay.setVisibility(View.VISIBLE); //make visible again
}
});
}
How do I change visibility from another method? I also cannot use static which I don't understand.
View should start from uppercase beacue it's class name:
seekBarTimeToPlay.setVisibility(View.GONE);
or
seekBarTimeToPlay.setVisibility(View.VISIBLE);
And remember about import:
import android.view.View;

Toggle VideoView's audio with a Button

I am using a videoView to play a video.
bVideoView = (VideoView) findViewById(R.id.bVideoView);
bVideoView.setVideoPath(videoPath);
Now I have a button,
audioToggle = (Button) findViewById(R.id.audioToggle);
Then I have the Button's OnClickListener
private static int aux = 0;
private AudioManager mAudioManager;
audioToggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bVideoView.start();
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
if(aux % 2 == 0){
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 50, 0);
aux++;
} else {
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
aux++;
}
}
});
Now with this OnClickListener I am perfectly able to toggle the audio to mute and unmute when it is clicked each time. However I want something like this,
On the first click the videoView should start.
When I keep pressing the button the audio must mute.
When I release the button the audio must unmute.
I have been trying a lot and failing in some or the other way. Please help.
Do you mean:
The first time I hold the button, the video should play.
While I'm holding the button the audio must be heard.
When I release the button, the audio must be muted.
When I press and hold the button again, the audio must be heard again.
Then what you therefore need is not an OnClickListener but rather an OnTouchListener
What happens under the hood is that your OnClickListener is always called after you release your finger. Using View.OnTouchListener you can dispatch events when you press (you mean touch and hold) and release.
See http://developer.android.com/reference/android/view/View.OnTouchListener.html
Here's a sample snippet:
private static int aux = 0;
private AudioManager mAudioManager;
audioToggle.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent e) {
bVideoView.start();
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch(e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 50, 0);
break;
case MotionEvent.ACTION_UP:
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
break;
}
return true;
}
}
Finally, I don't recommend controlling the system's volume. Use a MediaPlayer.OnPreparedListener instead, get the VideoView’s MediaPlayer and then play around with its volume.
Edit:
Here's another sample snippet:
private MediaPlayer bVideoViewMP;
bVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// Fetch a reference
bVideoViewMP = mp;
}
});
audioToggle.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent e) {
bVideoView.start();
switch(e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
bVideoViewMP.setVolume(0.75f, 0.75f);
break;
case MotionEvent.ACTION_UP:
bVideoViewMP.setVolume(0, 0);
break;
}
return true;
}
}
These should be placed either on your fragment's onViewCreated() or on your activity's onCreate() method before the VideoView has been fully prepared.

Saving data in application

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;
}
});
}}
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));
}
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();
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.

Button Down Event in Eclipse (Android)

I wanna use a button (not a key) just like backspace so when it is down do something repeatedly.
I've found proper code for hardware keys but as I mentioned I want a BUTTON do such things.
Thanks
You can set an OnTouchListener on a Button instance. You can then override the onTouch method of the of the listener to do what it is that you want until MotionEvent passed to the onTouch method has MotionEvent.getAction == MotionEvent.ACTION_UP. See this link for an example:
Android onTouch Listener event
A switch statement is sufficient, just customize it to fit your needs using what I said above. --hope this helps, Scott
Thanks Scott. Finally I found the answer and did the job.
public MyActivity extends Activity
{
private Handler mHandler = new Handler();
private Runnable mUpdateTask = new Runnable()
{
public void run()
{
Log.i("repeatBtn", "repeat click");
mHandler.postAtTime(this, SystemClock.uptimeMillis() + 100);
}
};
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button repeatButton = (Button) findViewById(R.id.repeatButton);
repeatButton.setOnTouchListener(new OnTouchListener()
{
public boolean onTouch(View view, MotionEvent motionevent)
{
int action = motionevent.getAction();
if (action == MotionEvent.ACTION_DOWN)
{
Log.i("repeatBtn", "MotionEvent.ACTION_DOWN");
mHandler.removeCallbacks(mUpdateTask);
mHandler.postAtTime(mUpdateTask, SystemClock.uptimeMillis() + 100);
}
else if (action == MotionEvent.ACTION_UP)
{
Log.i("repeatBtn", "MotionEvent.ACTION_UP");
mHandler.removeCallbacks(mUpdateTask);
}
return false;
}
});
}
}

Categories