Why not showing progressBar in Android Studio? - java

I was trying to work with Progressbar in android studio. What I wanted was simply that when I will click on the button of the MainActivity it will intent to a new activity called 'Progress'.
My activities are here:
MainActivity.java:
and Progress.java:
My app runs, but not showing any progressbar motion. What should I do to show progressbar for 30 sec? I am not doing anything in the meantime. I just want to see a progressbar for 30 sec.

1000 is too small for loop but this code do what you want :
//Set visible progres bar
findViewById(R.id.progress_bar).setVisibility(View.VISIBLE);
//Timer in your case 30 sek
int timer = 30*1000;
//create handler
final Handler handler = new Handler();
//set handler delayed
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Hidden progress bar
findViewById(R.id.progress_bar).setVisibility(View.INVISIBLE);
//your toast
Toast.makeText(this,"your msg",Toast.LENGTH_LONG).show();
//start new activity
startActivity(your intent)
}
}, timer);
}

mPrograssStatus is increasing to 100 in very short amount of time. You need to wait, for example try adding this to your code in loop while:
SystemClock.sleep(300);
value in brackets is amount of milliseconds that system will wait, in your case it is 300 to get 30 seconds. You also need to import library:
import android.os.SystemClock;

Related

How to make my stopwatch app running even after app has been closed completely?

How to make my stopwatch app running even after app has been closed completely ?
MainActivity.java
package com.study.meter;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import android.os.Handler;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
public TextView StopWatch;
public boolean isStopWatchRunning = false;
public int stopWatchSecs = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// hide actionbar
this.getSupportActionBar().hide();
// set the value of StopWatch
StopWatch = findViewById(R.id.StopWatch);
}
public void StartorStop(View v)
{
Button sv = (Button)v;
if(isStopWatchRunning)
{
isStopWatchRunning=false;
sv.setText("Start");
}else
{
isStopWatchRunning=true;
sv.setText("Stop");
}
// Creates a new Handler
final Handler handler
= new Handler();
// Call the post() method,
// passing in a new Runnable.
// The post() method processes
// code without a delay,
// so the code in the Runnable
// will run almost immediately.
handler.post(new Runnable() {
#Override
public void run()
{
int hours = stopWatchSecs / 3600;
int minutes = (stopWatchSecs % 3600) / 60;
int secs = stopWatchSecs % 60;
// Format the stopWatchSecs into hours, minutes,
// and stopWatchSecs.
String time
= String
.format(Locale.getDefault(),
"%d:%02d:%02d", hours,
minutes, secs);
// Set the text view text.
// If running is true, increment the
// stopWatchSecs variable.
if (isStopWatchRunning) {
StopWatch.setText(time);
stopWatchSecs++;
handler.postDelayed(this, 1000);
}
// Post the code again
// with a delay of 1 second.
}
});
}
}
This however restarts the stopWatch when app has been closed,
How to make this stopwatch not to stop after app has been closed or destroyed or device has been restarted or switched off?
I meant to say I want it to keep running in background
Edit
maybe like this mathematical equation
Time when app closed = 14:20:-00
StopWatch's reading when app closed = 23 secs
(save this data into storage)
Time when app reopend = 14:25:00
Last reading of stopwatch = 23 secs
so, value of stopwatch will be = (14:25:00 - 14:20:00)+23 secs = 5mins + 23 secs = 323secs
In theory, you could store the start time of the timer in a local storage and resume when the app starts again based on that value.
Try using JobScheduler to achieve this.
You have to make a Service that will run in the background. Whatsapp has a service in the background, so whenever a new notification comes and it is closed completely, then also notification appears.
See these links for reference:
Creating Background Service in Android
Android Developer Doc
Edit: Put your timer code inside a class that extends a Service

Can't understand disable button behavior

I'm new to android and pretty new to the concept of timing in Java also. I've tried to create a simple app that counts the number of user clicks on the screen in five seconds. After the time ends, I want to disable the button and restart everything when clicking the 'Restart' button.
This is the current code:
public void clickCounter(View view){
++counter;
if(showCounter!=null)
showCounter.setText(Integer.toString(counter));
}
public void clickTimer(final View view) {
final Button Tap = findViewById(R.id.Tap);
clickCounter(view);
new CountDownTimer(5000, 5000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
Tap.setEnabled(false);
}
}.start();
}
public void restartCounter(View view) {
counter=0;
showCounter.setText("Tap");
final Button Tap = findViewById(R.id.Tap);
Tap.setEnabled(true);
}
The button does disable after 5 seconds, but the restart button sometimes enables and then disables it right away (the counter and text changes properly).
I think the problem might be the way I'm using the Timer to do it (maybe I should use threads?)
You are creating a new timer on every button tap. So, when you reenable the button, one of your timers could be expiring, disabling the button afterwards. You should only create a new timer if there is none running.
To expand on Tiago Loureino's awesome answer, the problem is that you are creating a new CountDownTimer object every time the clickTimer() method is called.
The button does disable after 5 seconds, but the restart button sometimes enables and then disables it right away (the counter and text changes properly).
This 👆🏽 happens because you have several CountDownTimers executing their onFinish() method.
The solution to this problem is to have one single instance of your CountDownTimer. To put that in code, you can declare your CountDownTimer as below:
public CountDownTimer cdt = new CountDownTimer(5000, 5000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
Tap.setEnabled(false);
}
};
You can then call cdt.start() anytime you want to start your the timer.

How to hide View after a given time of inactivity

Basically I have a volume button that shows a hidden SeekBar when clicked, how to make the SeekBar go hidden again after 2 or 3 seconds of inactivity?
I just wanna know how can I check for how much time been spent since the SeekBar became visible without changing its progress!?
You could create a Runnable that sets the visibility of the SeekBar to invisible:
private final Runnable hideSeekBarRunnable = new Runnable() {
#Override
public void run() {
seekBar.setVisibility(View.INVISIBLE);
}
};
When the volume button is clicked, show the SeekBar and post the Runnable with a 2-3 sec delay:
seekBar.setVisibility(View.VISIBLE);
seekBar.postDelayed(hideSeekBarRunnable, 3000);
And if the SeekBar is interacted with (its progress changes), remove the pending Runnable and re-post it to reset the counter:
seekBar.removeCallbacks(hideSeekBarRunnable);
seekBar.postDelayed(hideSeekBarRunnable, 3000);

Android Countdown Timer in Broadcast receiver doesn't update TextView

I am creating application which works with SMS service and FTP networking.
If user does not establish connectivity, it will try to reconnect again in 30 seconds.
I am using CountDownTimer with TextView to inform user about time left to reconnnect.
Either it will be successful or it will start counting again.
My problem is, that if counter restarts while activity is in background or the screen is locked, TextView keeps showing number "1" (it won't update) until the timer restarts again in foreground (but updating numbers without timer restart works fine in backround or lock, I am using wakelock in my foreground service).
After counter restarts again (so it won't stop counting) while application is in foreground, everything comes back to normal, TextView updates from freezed "1" to "30" and starts counting down to "1".
I think problem will be somewhere in communication between counter thread and background activity with UI, but I don't know nothing more about it.
I tried several things like:
creating setter and getter for miliseconds and update them in each
tick, then try to update textview from onReume(), didn't work.
create local variable for TextView inside timer, initialize it inside onTick() and
try to update text from there, also didn't work.
Thanks everyone for help, I will appriciate any advices.
Part of code relative to question:
private CountDownTimer cdt = null;
private final TextView getTextView_ActivityMainMenu_Timer(){
return (TextView) findViewById(R.id.ActivityMainMenu_TextView_Timer);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getBooleanExtra("KEY_FAILED", false)){
cdt = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
getTextView_ActivityMainMenu_Timer().setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
;
}
}
.start();
}
else
{
if(cdt != null)
cdt.cancel();
}
}
};
Finally I found solution of this problem. I didn't realize that I am unregistering the receiver in onPause() method. So I had to change it and put registration of broadcast into onResume() and unregister it only in onDestroy() method.

timer.scheduleAtFixedRate does not stop when i call cancel

At onCreate, I run a task that repeats every minute. Here how I do it:
myTimer = new Timer();
int delay = 30000; // delay for 30 sec.
int period = 600000; // repeat every 60 sec.
doThis = new TimerTask() {
public void run() {
Log.v("TImer","repeated");
wv.reload();
}
};
myTimer.scheduleAtFixedRate(doThis, delay, period);
All that code is in onCreate. So, when the app goes off from the screen, I can see in logcat that timer steel runs, and will not stop unless the app will be destroyed. So, in onPause of activity I call myTimer.cancel(); but it didnt help. I still can see updates in logcat, even when the app is not on the screen. So, how to stop timerTask?
Here is your code put into my file, with the values delay and period tweaked so I don't have to wait so long. I run the app. I see the messages in LogCat. I press the home button on my Galaxy S3. Then the messages stop in LogCat.
public class MainActivity extends Activity {
Timer myTimer;
TimerTask doThis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTimer = new Timer();
int delay = 0; // delay for 30 sec.
int period = 1000; // repeat every 60 sec.
doThis = new TimerTask() {
public void run() {
Log.v("TImer","repeated");
}
};
myTimer.scheduleAtFixedRate(doThis, delay, period);
}
#Override
protected void onPause() {
myTimer.cancel();
super.onPause();
}
}
It could be that since the thread has already been sent out, it runs one last time. In the onLoad set a variable to true, then in the onPause set it to false. Then in your timer task only run your code if the variable is true.
Write to the log outside of the new if statement though. If it is indeed running it just one last time, then that might be your solution. But if it is still running it over and over multiple times after the onPause then don't take my solution.
The actual answer is: The onPause method needs to be defined correctly.
The whole story:
The questioner defined the onPause method wrong. That was the reason for asking this question.
I'm writing this because I spent too much time reading question, answers, code and comments. The real answer was hidden in the last comment.

Categories

Resources