Splash Screen Android - Count Down Timer Display - java

I am trying to use splash screen for my app.
I want to display Count down timer in my splash screen.
So far I am able to achieve the splash screen working but don't know how to display count down timer. I created layout for count down timer. I want splash screen to stay for 5 Hours then take to the next activity.
Splashactivity.java
public class splash_screen extends AppCompatActivity {
private float imageAplha = 1f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
//splashScreenUseTimer(5000);
splashScreenUseAsyncTask();
}
// Show splash screen until network load data complete.
private void splashScreenUseAsyncTask()
{
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
// Create a count down timer object.It will count down every 0.1 seconds and last for milliSeconds milliseconds..
CountDownTimer countDownTimer = new CountDownTimer(5000, 100) {
#Override
public void onTick(long l) {
// Reduce the splash screen background image's alpha value for each count down.
splashImageView.setAlpha(imageAplha);
imageAplha -= 0.1;
if(imageAplha <= 0)
{
imageAplha = 1;
}
}
#Override
public void onFinish() {
// When count down complete, set the image to invisible.
imageAplha = 0;
splashImageView.setAlpha(imageAplha);
// If AsyncTask is not complete, restart the counter to count again.
if(!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
// This is the async task class that get data from network.
private class RetrieveDateTask extends AsyncTask<String, String, String>{
// Indicate whether AsyncTask complete or not.
private boolean asyncTaskComplete = false;
public boolean isAsyncTaskComplete() {
return asyncTaskComplete;
}
public void setAsyncTaskComplete(boolean asyncTaskComplete) {
this.asyncTaskComplete = asyncTaskComplete;
}
// This method will be called before AsyncTask run.
#Override
protected void onPreExecute() {
this.asyncTaskComplete = false;
}
// This method will be called when AsyncTask run.
#Override
protected String doInBackground(String... strings) {
try {
// Simulate a network operation which will last for 10 seconds.
Thread currTread = Thread.currentThread();
for (int i = 0; i < 10; i++) {
currTread.sleep(1000);
}
}catch(Exception ex)
{
ex.printStackTrace();
}finally {
return null;
}
}
// This method will be called after AsyncTask run.
#Override
protected void onPostExecute(String s) {
// Start SplashScreenMainActivity.
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
this.asyncTaskComplete = true;
}
}
}
Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0"
android:background="#color/White"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<ImageView
android:id="#+id/logo_id"
android:layout_width="350dp"
android:layout_height="match_parent"
app:srcCompat="#drawable/ts_logo"
android:layout_gravity="center"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:orientation="vertical">
<LinearLayout
android:id="#+id/linear_layout_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/black"
android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/tv_hour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="00"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_hour_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hour"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="normal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/tv_minute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="00"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_minute_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Minute"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="normal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/tv_second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="00"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_second_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Second"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="normal" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>

#contact dummy I edited #Dev code with small modification.try this one. Based on your animation requirement increase and decrease imageAlpha size.
private float imageAplha = 1f;
private boolean imageStatus = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
splashScreenUseAsyncTask();
}
// Show splash screen until network load data complete.
private void splashScreenUseAsyncTask()
{
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
final TextView tv_hour = (TextView) findViewById(R.id.tv_hour);
final TextView tv_minute = (TextView) findViewById(R.id.tv_minute);
final TextView tv_second = (TextView) findViewById(R.id.tv_second);
// Create a count down timer object.It will count down every 0.1 seconds and last for milliSeconds milliseconds..
final int time= 3600000*5;
CountDownTimer countDownTimer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long l) {
long Days = l / (24 * 60 * 60 * 1000);
long Hours = l / (60 * 60 * 1000) % 24;
long Minutes = l / (60 * 1000) % 60;
long Seconds = l / 1000 % 60;
//
// tv_days.setText(String.format("%02d", Days));
tv_hour.setText(String.format("%02d", Hours));
tv_minute.setText(String.format("%02d", Minutes));
tv_second.setText(String.format("%02d", Seconds));
splashImageView.setAlpha(imageAplha);
if(imageStatus){
imageAplha += 1;
if(imageAplha >= 1)
{
// imageAplha-= 0.5;
imageStatus = false;
}
}else{
imageAplha -= 1;
if(imageAplha <= 0)
{
imageStatus = true;
}
}
}
#Override
public void onFinish() {
// When count down complete, set the image to invisible.
imageAplha = 0;
splashImageView.setAlpha(imageAplha);
// If AsyncTask is not complete, restart the counter to count again.
if(!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
// This is the async task class that get data from network.
private class RetrieveDateTask extends AsyncTask<String, String, String> {
// Indicate whether AsyncTask complete or not.
private boolean asyncTaskComplete = false;
public boolean isAsyncTaskComplete() {
return asyncTaskComplete;
}
public void setAsyncTaskComplete(boolean asyncTaskComplete) {
this.asyncTaskComplete = asyncTaskComplete;
}
// This method will be called before AsyncTask run.
#Override
protected void onPreExecute() {
this.asyncTaskComplete = false;
}
// This method will be called when AsyncTask run.
#Override
protected String doInBackground(String... strings) {
try {
// Simulate a network operation which will last for 10 seconds.
Thread currTread = Thread.currentThread();
for (int i = 0; i < 18000000; i++) {
currTread.sleep(1000);
}
}catch(Exception ex)
{
ex.printStackTrace();
}finally {
return null;
}
}
// This method will be called after AsyncTask run.
#Override
protected void onPostExecute(String s) {
// Start SplashScreenMainActivity.
Intent mainIntent = new Intent(splash_screen .this,
MainActvity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
this.asyncTaskComplete = true;
}
}
}

#contact dummy I have edited your code try using this
// Show splash screen until network load data complete.
private void splashScreenUseAsyncTask()
{
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
//for 5 Hours
final int time= 3600000*5;
CountDownTimer countDownTimer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long l) {
long Days = l / (24 * 60 * 60 * 1000);
long Hours = l / (60 * 60 * 1000) % 24;
long Minutes = l / (60 * 1000) % 60;
long Seconds = l / 1000 % 60;
//
tv_days.setText(String.format("%02d", Days));
tv_hour.setText(String.format("%02d", Hours));
tv_minute.setText(String.format("%02d", Minutes));
tv_second.setText(String.format("%02d", Seconds));
splashImageView.setAlpha(imageAplha);
imageAplha -= 0.1;
if(imageAplha <= 0)
{
imageAplha = 1;
}
}
#Override
public void onFinish() {
// When count down complete, set the image to invisible.
imageAplha = 0;
splashImageView.setAlpha(imageAplha);
// If AsyncTask is not complete, restart the counter to count again.
if(!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}

Related

Edit Text And Count Down Timer in Android Studio

I have a Counttimer and edittext on my app. I want write a number in edittext, and when I click button, then countdown timer will start, and the time is edittext variable. In XML, I have got an example number, because when I delete it, then it's not working. When I start countdown timer, then it works, but if I change edittext, then it uses the old edittext data. How can I solve my problem?
pomodoro.XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".pomodoro"
android:background="#drawable/backround_home">
<
<EditText
android:id="#+id/edittextcalisma"
android:layout_width="80dp"
android:layout_height="40dp"
android:text="20"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="25dp"
android:background="#drawable/edittext"
android:layout_marginLeft="30dp"
android:visibility="visible"
android:inputType="number"
android:maxLength="2"
android:lines="1"
/>
<EditText
android:id="#+id/edittextmola"
android:layout_width="80dp"
android:layout_height="40dp"
android:text="5"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="25dp"
android:background="#drawable/edittext"
android:visibility="visible"
android:layout_marginLeft="30dp"
android:inputType="number"
android:maxLength="2"
android:lines="1"
/>
<Button
android:id="#+id/baslatbutton"
android:layout_width="150dp"
android:layout_height="50dp"
android:text="Başla"
android:textSize="25dp"
android:layout_marginTop="400dp"
android:textColor="#ffffff"
android:fontFamily="#font/montserrat_regular"
android:background="#drawable/button"
android:layout_centerHorizontal="true"
android:visibility="visible"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40dp"
android:layout_centerInParent="true"
android:fontFamily="#font/montserrat_regular"
android:textColor="#000000"
android:id="#+id/pomodoro"
android:visibility="invisible"
/>
</RelativeLayout>
Java.class
public class pomodoro extends AppCompatActivity {
Button baslat;
EditText edittextcalisma,edittextmola;
TextView textcalisma,textmola,pomodoro;
CountDownTimer calisma,mola;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pomodoro);
baslat = findViewById(R.id.baslatbutton);
edittextcalisma = findViewById(R.id.edittextcalisma);
edittextmola = findViewById(R.id.edittextmola);
textcalisma = findViewById(R.id.textcalisma);
textmola = findViewById(R.id.textmola);
String timercalisma = edittextcalisma.getText().toString();
String timermola = edittextmola.getText().toString();
long calismapo = Long.parseLong(timercalisma) * 60000;
long molapo = Long.parseLong(timermola) * 60000;
pomodoro = findViewById(R.id.pomodoro);
baslat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pomodoro.setVisibility(View.VISIBLE);
calisma.start();
}
});
calisma = new CountDownTimer(calismapo, 1000) {
#Override
public void onTick(long millis) {
int minuted1 = (int) (millis / 1000) / 60;
int secondd1 = (int) (millis / 1000) % 60;
pomodoro.setText(minuted1 + ":" + secondd1);
if (secondd1 < 10) {
pomodoro.setText(minuted1 + ":0" + secondd1);
}
}
#Override
public void onFinish() {
calisma.cancel();
mola.start();
}
};
mola = new CountDownTimer(molapo, 1000) {
#Override
public void onTick(long molapo) {
int minuted1 = (int) (molapo / 1000) / 60;
int secondd1 = (int) (molapo / 1000) % 60;
pomodoro.setText(minuted1 + ":" + secondd1);
if (secondd1 < 10) {
pomodoro.setText(minuted1 + ":0" + secondd1);
}
}
#Override
public void onFinish() {
mola.cancel();
pomodoro.setText("Bitti");
}
};
}
}
and the time is edittext variable. In XML, I have got an example
number, because when I delete it, then it's not working.
Because you read your EditText fields in the onCreate and your code expects a number, then that is why you need to set the "example" numbers in XML.
When you remove the number from XML, you either need to:
check for null
String timercalisma = edittextcalisma.getText().toString();
String timermola = edittextmola.getText().toString();
if(timercalisma == null || timercalisma.isEmpty()) {
timercalisma = "0";
}
if(timermola == null || timermola.isEmpty()) {
timermola = "0";
}
long calismapo = Long.parseLong(timercalisma) * 60000;
long molapo = Long.parseLong(timermola) * 60000;
or read the fields on button press
baslat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String timercalisma = edittextcalisma.getText().toString();
String timermola = edittextmola.getText().toString();
long calismapo = Long.parseLong(timercalisma) * 60000;
long molapo = Long.parseLong(timermola) * 60000;
pomodoro.setVisibility(View.VISIBLE);
calisma.start();
}
});

Android Studio: how progress bar can fill up based on user input

I am using a progress bar sample from Github however I noticed that the progress bar fill is set to a fixed value. For example, if the step count goal is 10 (.java class) the man should be "10" in the .XML
My goal: when the user inputs their goal step count, the "10" should be variable and change depending on user input.
java snippet:
ProgressBar progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", lastStep, stepCounter); //animate only from last known step to current step count
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();
lastStep = stepCounter;
XML snippet
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="376dp"
android:layout_height="392dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:max="10"
android:progress="0"
android:progressDrawable="#drawable/circular" />
EDIT********************EDIT
Sorry maybe my question wasn't clear. To provide an example...if the users step goal is 500. I need the progress bar to fill respectively. Therefore, IF step_count = 250 then progress bar should be half full, IF step_count = 750 then should be 3/4 full. I need the progression to be respective to a variable value.
Set android:indeterminate="false". See this fully implemented code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ProgressBar
android:id="#+id/pBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="200dp"
android:minHeight="50dp"
android:minWidth="200dp"
android:max="100"
android:indeterminate="false"
android:progress="0" />
<TextView
android:id="#+id/tView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/pBar"
android:layout_below="#+id/pBar" />
<Button
android:id="#+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="130dp"
android:layout_marginTop="20dp"
android:text="Start Progress"
android:layout_below="#+id/tView"/>
public class MainActivity extends AppCompatActivity {
private ProgressBar pgsBar;
private int i = 0;
private TextView txtView;
private Handler hdlr = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pgsBar = (ProgressBar) findViewById(R.id.pBar);
txtView = (TextView) findViewById(R.id.tView);
Button btn = (Button)findViewById(R.id.btnShow);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = pgsBar.getProgress();
new Thread(new Runnable() {
public void run() {
while (i < 100) {
i += 1;
// Update the progress bar and display the current value in text view
hdlr.post(new Runnable() {
public void run() {
pgsBar.setProgress(i);
txtView.setText(i+"/"+pgsBar.getMax());
}
});
try {
// Sleep for 100 milliseconds to show the progress slowly.
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
}
}

setText function does not change the TextView

the app runs the way I want I can see that in the Logcat
but the text view is not changing and keeps the default value
i also tried to change button enable status programmatically but stayed in the same , nothing get changed !!
I tried in the setText method both
String.valueof(int)
and
Integer.toString(int)
java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play =(Button) findViewById(R.id.button4);
Pause =(Button) findViewById(R.id.button5);
hourstext =(TextView) findViewById(R.id.textView1);
mintext =(TextView) findViewById(R.id.textView2);
sectext =(TextView) findViewById(R.id.textView3);
}
void playb(View v) {
while (!ispause) {
sec = 0 ;
while (sec < 60) {
SystemClock.sleep(1000);
sec++;
sectext.setText(Integer.toString(sec));
Log.d("this", "sec value=" + sec);
}
sec = 0;
min++;
Log.d("this","min value ="+min);
mintext.setText(String.valueOf(min));
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView3"
android:layout_width="114dp"
android:layout_height="94dp"
android:layout_marginTop="159dp"
android:layout_marginEnd="16dp"
android:layout_x="274dp"
android:layout_y="120dp"
android:gravity="center|center_horizontal"
android:text="00"
android:textSize="40sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/pauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="72dp"
android:layout_marginTop="116dp"
android:layout_marginEnd="93dp"
android:layout_x="217dp"
android:layout_y="296dp"
android:enabled="false"
android:onClick="playb"
android:text="Pause"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/playbutton"
app:layout_constraintTop_toBottomOf="#+id/textView3" />
<Button
android:id="#+id/playbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="70dp"
android:layout_marginTop="116dp"
android:layout_x="63dp"
android:layout_y="293dp"
android:onClick="playb"
android:text="playb"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
<TextView
android:id="#+id/textView2"
android:layout_width="120dp"
android:layout_height="97dp"
android:layout_marginTop="156dp"
android:layout_marginEnd="17dp"
android:layout_x="139dp"
android:layout_y="117dp"
android:gravity="center|center_horizontal"
android:text="00"
android:textSize="40sp"
app:layout_constraintEnd_toStartOf="#+id/textView3"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView1"
android:layout_width="103dp"
android:layout_height="94dp"
android:layout_marginStart="16dp"
android:layout_marginTop="159dp"
android:layout_x="11dp"
android:layout_y="117dp"
android:gravity="center_horizontal|center_vertical"
android:text="00"
android:textSize="40sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
i get no error message ! the app keeps working but no updated textView
i've included my XML Code
It's likely to do with running everything on the main thread. You should never call sleep on the main thread or you will block the UI.
When the button is clicked you should start the counter on a background thread. You will then need to update the TextView on the main thread.
It can be achieved quite easily with RxJava:
private Disposable disposable;
disposable = Observable.interval(1, 1, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(value -> {
// Update UI
});
To stop the counter:
disposable.dispose();
If you want make counter up for 60 sec you can use this code
long time=60;
new CountDownTimer(time*1000, 1000)
{
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds : " + (time-millisUntilFinished /1000));
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Before trying to fix this problem, let first understand why it happens
CAUSE
When you call View.setText(), Android doesn't actually set the text immediately. It pushes all of these set-text works to a queue on main thread to do LATER whenever it has free time.
Let's try to run this block, you will notice that until this while loop finish, View.setText() will not be done.
void playb(View v) {
min = 0
while (min < 1000000) {
min++
Log.d("this", "min value =$min")
mintext.setText(String.valueOf(min))
}
}
So in your situtation, actually the TextView will still be set, but you will not see the change until the while loop finishes.
SOLUTION
You should move this while loop to another thread, you can simply use an AsyncTask or a HandlerThread for that
Ex. Use a HandlerThread:
void playb() {
// Start a new background thread
HandlerThread thread = new HandlerThread("");
thread.start();
// Obtain the handler of new background thread
Handler handler = new Handler(thread.getLooper());
// Obtain the handler of main thread (UI Thread)
final Handler mainHandler = new Handler(this.getMainLooper());
// Create a runnable and send it to background thread to execute
handler.post(new Runnable() {
public final void run() {
// Do the job
int min = 0;
while(true) {
int sec = 0;
while(sec < 60) {
SystemClock.sleep(1000L);
sec ++;
final int currentSec = sec;
// Send the update-text job to main thread to execute
mainHandler.post(new Runnable() {
public final void run() {
secText.setText(currentSec);
}
});
}
sec = 0;
min++;
final int currentMin = min;
// Send the update-text job to main thread to execute
mainHandler.post(new Runnable() {
public final void run() {
minText.setText(currentMin);
}
});
}
}
});
}

How to efficiently put a multitude of stopwatches on one activity?

I made a single working stopwatch, but I can't figure out a way to add several to the same page. What would be an effective way to do this? I tried copying the code and changing all the parameters but that did not seem to work.
The code I have at the moment:
XML
<RelativeLayout
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<EditText
android:id="#+id/topTextInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_toLeftOf="#+id/timeOne"
android:layout_toStartOf="#+id/timeOne"
android:width="300dp"
android:elevation="1dp" />
<TextView
android:id="#+id/timeOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/topTextInput"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginEnd="13dp"
android:layout_marginRight="13dp"
android:layout_marginTop="50dp"
android:clickable="false"
android:elevation="4dp"
android:text="00:00:00"
android:textSize="24sp"
android:visibility="visible" />
<Button
android:id="#+id/stopbuttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/topTextInput"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/topTextInput"
android:layout_toEndOf="#+id/topTextInput"
android:layout_toRightOf="#+id/topTextInput"
android:width="110dp"
android:background="#android:color/darker_gray"
android:onClick="stopClick"
android:text=""
android:visibility="invisible" />
<Button
android:id="#+id/startbuttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/topTextInput"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/topTextInput"
android:layout_toEndOf="#+id/topTextInput"
android:layout_toRightOf="#+id/topTextInput"
android:width="120dp"
android:onClick="startClick"
android:text=""
android:visibility="visible" />
<Button
android:id="#+id/resetButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Reset"
android:onClick="resetClick" />
<TextView
android:id="#+id/millitimeOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/timeOne"
android:visibility="visible" />
</RelativeLayout>
Java:
package com.keur.joran.time;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
private TextView tempTextView; //Temporary TextView
private Button tempBtn; //Temporary Button
private Handler mHandler = new Handler();
private Handler m2Handler = new Handler();
private long startTime;
private long elapsedTime;
private long start2Time;
private long elapsed2Time;
private final int REFRESH_RATE = 100;
private String hours,minutes,seconds,milliseconds;
private long secs,mins,hrs,msecs;
private boolean stopped = false;
private Runnable startTimer = new Runnable() { public void run() { elapsedTime = System.currentTimeMillis() - startTime; updateTimer(elapsedTime); mHandler.postDelayed(this,REFRESH_RATE); } };
private Runnable start2Timer = new Runnable() { public void run() { elapsed2Time = System.currentTimeMillis() - start2Time; updateTimer(elapsed2Time); mHandler.postDelayed(this,REFRESH_RATE); } };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void stopClick (View view){ hideStopButton(); mHandler.removeCallbacks(startTimer); stopped = true; }
public void startClick (View view){ showStopButton(); if(stopped){ startTime = System.currentTimeMillis() - elapsedTime; } else{ startTime = System.currentTimeMillis(); } mHandler.removeCallbacks(startTimer); mHandler.postDelayed(startTimer, 0); }
public void resetClick (View view){ stopped = false; ((TextView)findViewById(R.id.timeOne)).setText("00:00:00"); ((TextView)findViewById(R.id.millitimeOne)).setText(".0"); }
private void showStopButton(){ ((Button)findViewById(R.id.startbuttonOne)).setVisibility(View.GONE);
((Button)findViewById(R.id.stopbuttonOne)).setVisibility(View.VISIBLE);
}
private void hideStopButton(){ ((Button)findViewById(R.id.startbuttonOne)).setVisibility(View.VISIBLE);
((Button)findViewById(R.id.stopbuttonOne)).setVisibility(View.GONE);
}
private void updateTimer (float time){ secs = (long)(time/1000);
mins = (long)((time/1000)/60); hrs = (long)(((time/1000)/60)/60);
/* Convert the seconds to String * and format to ensure it has * a leading zero when required */
secs = secs % 60;seconds=String.valueOf(secs);
if(secs == 0){ seconds = "00"; } if(secs <10 && secs > 0){ seconds = "0"+seconds;
}
/* Convert the minutes to String and format the String */ mins = mins % 60; minutes=String.valueOf(mins); if(mins == 0){ minutes = "00"; } if(mins <10 && mins > 0){ minutes = "0"+minutes; } /* Convert the hours to String and format the String */ hours=String.valueOf(hrs); if(hrs == 0){ hours = "00"; } if(hrs <10 && hrs > 0){ hours = "0"+hours; } /* Although we are not using milliseconds on the timer in this example * I included the code in the event that you wanted to include it on your own */ milliseconds = String.valueOf((long)time); if(milliseconds.length()==2){ milliseconds = "0"+milliseconds; } if(milliseconds.length()<=1){ milliseconds = "00"; } milliseconds = milliseconds.substring(milliseconds.length()-3, milliseconds.length()-2); /* Setting the timer text to the elapsed time */ ((TextView)findViewById(R.id.timeOne)).setText(hours + ":" + minutes + ":" + seconds); ((TextView)findViewById(R.id.millitimeOne)).setText("." + milliseconds); }
}
Turn the stopwatch into either a custom view or fragment. Then you should only need to include the view/fragment in the xml, and call the appropriate event handler functions you added in the java code.

The timer not let the user to edit

I'm a begginer and i build a timer app and i want the app to allow the user to edit the time. like in the android build in timer. and i wrote the code and it not really works it's show like it can be edit but when i'm trying to write something, it's change for a sec and go back to what it's been before..
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_stopwatch"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.adir.stopwatch.StopwatchActivity"
android:background="#000000"
>
<Button
android:id="#+id/reset_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickReset"
android:text="#string/reset"
android:textColor="#FFFFFF"
android:layout_below="#+id/stop_button"
android:layout_alignLeft="#+id/stop_button"
android:layout_alignStart="#+id/stop_button" />
<EditText
android:id="#+id/time_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="17dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="92sp"
android:textColor="#FFFFFF"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:inputType="time"
/>
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickStart"
android:text="#string/start"
android:textColor="#FFFFFF"
android:layout_below="#+id/time_view"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp" />
<Button
android:id="#+id/stop_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickStop"
android:text="#string/stop"
android:textColor="#FFFFFF"
android:layout_alignLeft="#+id/start_button"
android:layout_alignStart="#+id/start_button"
android:layout_below="#+id/start_button"></Button>
</RelativeLayout>
Java:
public class StopwatchActivity extends Activity {
private int seconds=0;
private boolean running;
private boolean wasRunning;
public String time;
public int hours=seconds/3600;
public int minutes=(seconds%3600)/60;
public int secs=seconds%60;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
if(savedInstanceState!=null){
seconds=savedInstanceState.getInt("seconds");
running=savedInstanceState.getBoolean("running");
wasRunning=savedInstanceState.getBoolean("wasRunning");
}
runTimer();
}
public void onClickStart(View view) {
running = true;
}
protected void onStop(){
super.onStop();
wasRunning=running;
running=false;
}
protected void onStart() {
super.onStart();
if(wasRunning){
running=true;
}
}
public void onClickStop(View view) {
running = false;
}
public void onClickReset(View view) {
running = false;
seconds = 0;
}
private void runTimer() {
final EditText timeView = (EditText) findViewById(R.id.time_view);
time=timeView.getText().toString();
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
time = String.format("%d:%02d:%02d",hours, minutes, secs);
timeView.setText(time);
if (running) {
seconds--;
}
handler.postDelayed(this, 1000);
}
});
}
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putInt("seconds",seconds);
savedInstanceState.putBoolean("running",running);
savedInstanceState.putBoolean("wasRunning",wasRunning);
}
protected void onPause(){
super.onPause();
wasRunning=running;
running=false;
}
protected void onResume(){
super.onResume();
if(wasRunning){
running=true;
}
}
}
What do i need to fix?
The code below will give you a good idea of what to do. When you click the button, it will get the text of the EditText and put it into string. Then it will convert into int. Then you can put the new int variable time into your CountDownTimer function's 1st parameter to set the length of the timer.
Button submit;
TextView timerText;
EditText editTextTime;
CountdownTimer yourTimer;
String timeString;
int time;
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timeString = String.valueOf(editTextTime.getText());
time = Integer.valueOf(timeString);
}
});
yourTimer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long millisUntilFinished) {
int seconds = (int) millisUntilFinished / 1000;
int minutes = seconds / 60;
seconds %= 60;
minutes %= 60;
if (seconds < 10 && seconds >= 1) {
timerText.setText("" + seconds);
}
}
#Override
public void onFinish() {
}
}.start();

Categories