I am pretty new to android and am making a timer app (The code is not complete, as you can see, but I am testing on thing at a time). hitting the start button a second time results in the app closing out. I edited my code so that the timer is being recreated each call to onClick, but the app still closes out after the second click. Thank you for the help.
package com.example.ryan.timerapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
secondsView = (TextView) findViewById(R.id.seconds);
tenSecondsView = (TextView) findViewById(R.id.tensSeconds);
hoursView = (TextView) findViewById(R.id.hours);
tenHoursView = (TextView) findViewById(R.id.tensHours);
minutesView = (TextView) findViewById(R.id.minutes);
tenMinutesView = (TextView) findViewById(R.id.tensMinutes);
timer = new Timer();
}
TextView secondsView;
TextView tenSecondsView;
TextView hoursView;
TextView tenHoursView;
TextView minutesView;
TextView tenMinutesView;
Timer timer;
TimerTask timerTask;
public void start(View view){
if(timer != null) {
timerTask.cancel();
timer.cancel();
}
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Thread(new Runnable() {
#Override
public void run() {
int secondsInt = Integer.parseInt(secondsView.getText().toString());
int tenSecondsInt = Integer.parseInt(tenSecondsView.getText().toString());
int hoursInt = Integer.parseInt(hoursView.getText().toString());
int tenHoursInt = Integer.parseInt(tenHoursView.getText().toString());
int minutesInt = Integer.parseInt(minutesView.getText().toString());
int tenMinutesInt = Integer.parseInt(tenMinutesView.getText().toString());
if (secondsInt < 9) {
secondsInt++;
secondsView.setText(secondsInt + "");
} else {
secondsInt = 0;
secondsView.setText(secondsInt + "");
if (tenSecondsInt < 6) {
tenSecondsInt++;
tenSecondsView.setText(tenSecondsInt + "");
} else {
tenSecondsInt = 0;
tenSecondsView.setText(tenSecondsInt + "");
if (minutesInt < 9) {
minutesInt++;
minutesView.setText(minutesInt + "");
} else {
minutesInt = 0;
minutesView.setText(minutesInt + "");
}
}
}
}
}));
}
};
timer.scheduleAtFixedRate(timerTask,0, 1000);
}
public void stop(View view){
timer.cancel();
}
public void reset(View view){
secondsView.setText("0");
tenSecondsView.setText("0");
minutesView.setText("0");
tenMinutesView.setText("0");
hoursView.setText("0");
tenHoursView.setText("0");
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.ryan.timerapp.MainActivity"
android:layout_margin="5dp"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="35sp"
android:text="Timer"
android:gravity="center"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_weight="2"
>
<TextView
android:id="#+id/tensHours"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="35sp"
android:text="0"
/>
<TextView
android:id="#+id/hours"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="35sp"
android:text="0"
/>
<TextView
android:id="#+id/firstColon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="35sp"
android:text=":"
/>
<TextView
android:id="#+id/tensMinutes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="35sp"
android:text="0"
/>
<TextView
android:id="#+id/minutes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="35sp"
android:text="0"
/>
<TextView
android:id="#+id/secondColon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text=":"
/>
<TextView
android:id="#+id/tensSeconds"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="35sp"
android:text="0"
/>
<TextView
android:id="#+id/seconds"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="35sp"
android:text="0"
/>
</LinearLayout>
<Button
android:id="#+id/startButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="START"
android:textSize="30sp"
android:onClick="start"
/>
<Button
android:id="#+id/stopButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="STOP"
android:textSize="30sp"
android:onClick="stop"
/>
<Button
android:id="#+id/resetButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_weight="2"
android:text="RESET"
android:textSize="30sp"
android:onClick="reset"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
</LinearLayout>
the first being the Seconds counter not updating past 1 second
TimerTask is used to run a particular task at a specified time.
timer.schedule() is not meant to run continuously.
Check this documentation.
So this block of code-
int secondsInt = Integer.parseInt(txt.getText().toString());
secondsInt++;
if(secondsInt<=6) {
txt.setText(secondsInt + "");
}
will run only once . Hence
Seconds counter not updating past 1 second
is the apparent behavior.
hitting the start button a second time results in the app closing out
You are trying to run an already scheduled TimerTask.
You need to create a new Timer instance to start your TimerTask again.
Change your start() method -
public void start(View view){
if(timer != null) {
timerTask.cancel();
timer.cancel();
}
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Thread(new Runnable() {
#Override
public void run() {
int secondsInt = Integer.parseInt(txt.getText().toString());
secondsInt++;
if(secondsInt<=6) {
seconds.setText(secondsInt + "");
}
}
}));
}
};
timer.scheduleAtFixedRate(timerTask,0, 1000);
}
Also, no need to initialize your TextView again and again . Do it once only in onCreate() -
private TextView seconds;
private Timer timer;
private TimerTask timerTask;
In onCreate()
seconds = (TextView) findViewById(R.id.seconds);
Related
I am trying to generate Multiplication Table of any number that is input by user. I have developed the interface for the application but cannot understand where to start with the logical part(coding). What i want is when a user inputs a number into the EditText then in the TextView (id: printArea) should show the table of the input number in the format as given in image 2. [Just to show you example i used TextView in the printArea part and i do not know what to use instead]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:weightSum="1">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="Please Enter a Number: "
android:textSize="20sp" />
<EditText
android:id="#+id/num"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginLeft="30dp"
android:textSize="20sp" />
</LinearLayout>
<Button
android:id="#+id/calculate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/log"
android:onClick="submitNumber"
android:text="Get Table" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:id="#+id/printArea" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/clear"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="1dp"
android:text="Clear" />
<Button
android:id="#+id/credits"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:text="Credits" />
<Button
android:id="#+id/exit"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginRight="2dp"
android:text="Exit" />
</LinearLayout>
</LinearLayout>
and the MainActivity.java is:
package com.example.tara.multiplicationtable;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText num;
Button credits;
Button calculate;
Button clear;
Button exit;
TextView printArea;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num = new EditText(this);
clear = new Button(this);
calculate = new Button(this);
credits = new Button(this);
calculate = new Button(this);
printArea = new TextView(this);
num = (EditText) findViewById(R.id.num);
credits = (Button) findViewById(R.id.credits);
clear = (Button) findViewById(R.id.clear);
exit = (Button) findViewById(R.id.exit);
printArea = (TextView) findViewById(R.id.printArea);
calculate = (Button) findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//change the integer value into string
int num1 = Integer.parseInt(num.getText().toString());
// Perform action on click
for (int i = 1; i <= 10; i++) {
printArea.setText(num1 + "X" + i + "=" + i * num1);
}
}
});
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num.setText("");
}
});
credits.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Credits.class);
startActivity(i);
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
System.exit(0);
}
});
}
}
when application is launched it should show like thisThe initial state of application
and i want to make the application show the table like this if user input is 2 The Final Result
Make a Listview and then in its adapter add your table data.
Make adapter's layout like this:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="*" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="=" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4" />
Here are the codes that i used to build the Multiplication Table that i imagined to build. The code for activity_main.xml file will be:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginEnd="1dp"
android:layout_marginStart="2dp"
android:text="#string/Enter_number"
android:textSize="16sp" />
<EditText
android:id="#+id/num"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginEnd="2dp"
android:layout_marginStart="1dp"
android:digits="0123456789"
android:hint="#string/hidden_text"
android:inputType="number"
android:maxLength="3"
android:textSize="16sp" />
</LinearLayout>
<Button
android:id="#+id/calculate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/calculate"
android:imeOptions="actionDone"
android:textSize="16sp"/>
<!--android:onClick="submitNumber"-->
<TextView
android:id="#+id/printArea"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="20sp"
android:background="#drawable/backimage" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginEnd="1dp"
android:layout_marginStart="2dp"
android:textSize="16sp"
android:text="#string/clear"
/>
<Button
android:id="#+id/credits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginEnd="1dp"
android:layout_marginStart="1dp"
android:textSize="16sp"
android:text="#string/credits" />
<Button
android:id="#+id/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="2dp"
android:layout_marginStart="1dp"
android:layout_weight="1"
android:textSize="16sp"
android:text="#string/exit" />
</LinearLayout>
</LinearLayout>
The Code for the MainActivity.java file will be:
package com.example.tara.multiplicationtable;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText num;
Button credits;
Button calculate;
Button clear;
Button exit;
TextView printArea;
//private static final String result = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num = new EditText(this);
clear = new Button(this);
calculate = new Button(this);
credits = new Button(this);
calculate = new Button(this);
printArea = new TextView(this);
num = (EditText) findViewById(R.id.num);
credits = (Button) findViewById(R.id.credits);
clear = (Button) findViewById(R.id.clear);
exit = (Button) findViewById(R.id.exit);
calculate = (Button) findViewById(R.id.calculate);
printArea = (TextView) findViewById(R.id.printArea);
calculate.setOnClickListener(new View.OnClickListener() {
// Perform action on Get Table Button click
public void onClick(View v) {
if (num.getText().length() == 0 ){
printArea.setText(R.string.err_msg);
}
else {
//change the integer value into string
printArea.setText("");
int num1 = Integer.parseInt(num.getText().toString());
String result;
for (int i = 1; i <= 10; i++) {
result = (num1 + " X " + i + " = " + i * num1);
printArea.append("\n" + result);
}
}
}
});
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num.setText("");
printArea.setText("");
}
});
credits.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Credits.class));
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Good Bye, User!", Toast.LENGTH_SHORT).show();
finish();
}
});
}
}
Thank you everyone for the guidance.
I made an app that counts the scored goals in a match (When you're playing with friends and you're too lazy to count the scores :D ) I want to make a countdown timer to count the time for the match.
My app crashes when I push a Start button to start the countdown timer.I have 2 Activities.The Main activity is the code that counts the scores for the 2 teams.
This is my Second Activity code(Where the CountDowntimer should be.):
package com.example.robert.scorecount;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.concurrent.TimeUnit;
public class SecondActivity extends AppCompatActivity {
Button StartButton,StopButton;
TextView TimerText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button StartButton = (Button) findViewById(R.id.StartButton);
Button StopButton = (Button) findViewById(R.id.StopButton);
TextView TimerText = (TextView) findViewById(R.id.Timer);
TimerText.setText("00:00:00");
final CounterClass timer = new CounterClass(3600000,1000);
assert StartButton != null;
StartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer.start();
}
});
assert StopButton != null;
StopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer.cancel();
}
});
}
public class CounterClass extends CountDownTimer{
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
String HourMinutesSeconds = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
TimerText.setText(HourMinutesSeconds);
}
#Override
public void onFinish() {
TimerText.setText("Finished.");
}
}
}
And This is my layout code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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.example.robert.scorecount.SecondActivity">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Timer Settings"
android:id="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:textSize="20dp"
android:textAlignment="center" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start"
android:id="#+id/StartButton"
android:layout_marginBottom="37dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00"
android:id="#+id/Timer"
android:textSize="30dp"
android:layout_marginTop="88dp"
android:layout_below="#+id/ThirtyMinMatch"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Stop"
android:id="#+id/StopButton"
android:layout_above="#+id/StartButton"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="30 Minutes"
android:id="#+id/ThirtyMinMatch"
android:layout_marginTop="24dp"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/Timer"
android:layout_toStartOf="#+id/Timer" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 Hour"
android:id="#+id/OneHourMinMatch"
android:layout_alignTop="#+id/ThirtyMinMatch"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toRightOf="#+id/Timer"
android:layout_toEndOf="#+id/Timer" />
</RelativeLayout>
Your code:
TextView TimerText = (TextView) findViewById(R.id.Timer);
Change this line and just delete "TextView", it's already on top.
TimerText = (TextView) findViewById(R.id.Timer);
How to create an android mobile application that will do a counting in miliseconds (start from 0), and ask user to type"I Like to eat" in EditText and click submit. After user click submit, counting will stop and a dialog box will appear and show the counting result.
package com.example.labex4;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
TextView textView1,textView2,textView3,textView4,displayValue;
EditText nameTxt;
Button button1;
int count = 0;
Timer T;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable()
{
#Override
public void run()
{
displayValue.setText("count="+count);
count++;
}
});
}
}, 0, 1);
textView1 = (TextView)findViewById(R.id.textView1);
textView2 = (TextView)findViewById(R.id.textView2);
textView3 = (TextView)findViewById(R.id.textView3);
textView4 = (TextView)findViewById(R.id.textView4);
displayValue = (TextView)findViewById(R.id.displayValue);
nameTxt = (EditText)findViewById(R.id.nameTxt);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
T.cancel();
dialog.editext.setText(""+count);
}
}
***Here is The XML file***
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="(Type Faster)"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="25dp"
android:text="Miliseconds: " />
<TextView
android:id="#+id/displayValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView2"
android:layout_toRightOf="#+id/textView2"
android:text="displayvalue" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:text="Type this words: " />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="Frankie Jones Anak Saing"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/nameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView4"
android:layout_marginTop="38dp"
android:ems="10" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/nameTxt"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:text="Check" />
</RelativeLayout>
Global Variable
int count = 0;
Timer T;
Put the below code in onCreate after setContentView
T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable()
{
#Override
public void run()
{
//myTextView.setText("count="+count);
count++;
}
});
}
}, 0, 1);
At Button OnCLick
UPDATE
T.cancel();
//Open popup or dialog or alert as per your choice and print the count value
//dialog.editext.setText(""+count);
AlertDialog alertDialog = new AlertDialog.Builder(<YourActivityName>this).create(); //Read Update
alertDialog.setTitle("You total time count");
alertDialog.setMessage(String.valueof(count));
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
alertDialog.dismiss();
}
});
alertDialog.show(); //<-- See This!
}
As Per Your Requirement I am pasting the whole class
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity implements OnClickListener {
TextView textView1,textView2,textView3,textView4,displayValue;
EditText nameTxt;
Button button1;
int count = 0;
Timer T;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T=new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable()
{
#Override
public void run()
{
displayValue.setText("count="+count);
count++;
}
});
}
}, 0, 1);
textView1 = (TextView)findViewById(R.id.textView1);
textView2 = (TextView)findViewById(R.id.textView2);
textView3 = (TextView)findViewById(R.id.textView3);
textView4 = (TextView)findViewById(R.id.textView4);
displayValue = (TextView)findViewById(R.id.displayValue);
nameTxt = (EditText)findViewById(R.id.nameTxt);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
T.cancel();
//Open popup or dialog or alert as per your choice and print the count value
//dialog.editext.setText(""+count);
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_popup);
dialog.setTitle("Typing Result!");
// set the custom dialog components - text, image and button
TextView titletext = (TextView) dialog.findViewById(R.id.titletext);
//titletext.setText("Typing Result!");
titletext.setVisibility(View.GONE);
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Frankie Jones Igat, Your Typing Speed "+String.valueOf(count)+" miliseconds");
Button dialogButtonOK = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButtonOK.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
And Custom pop up layout in layout folder custom_popup.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#999999"
android:layout_marginTop="10dp">
<TextView
android:id="#+id/titletext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="title"
android:textSize="18sp"
android:textColor="#android:color/black"/>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/titletext"
android:layout_marginTop="5dp"
android:textSize="16sp"
android:text="titlekiefsjisejefsjeaij"
android:textColor="#android:color/black"
android:layout_centerHorizontal="true"
/>
<Button
android:id="#+id/dialogButtonOK"
android:layout_width="80dp"
android:layout_height="40dp"
android:text=" Ok "
android:layout_marginTop="10dp"
android:layout_marginRight="5dp"
android:layout_below="#+id/text"
android:textSize="18sp"
android:textColor="#android:color/black"
android:layout_centerHorizontal="true"
android:gravity="center"
android:background="#FF0000"
android:layout_marginBottom="10dp"
/>
</RelativeLayout>
I have made a Timer Application in android.In application there are three (uneditable)EditText and a Button.When i press Button first time the timer in 1st EditText will start ,when i press it 2nd time the timer in 1st EditText will stop and at the same time the timer in 2nd EditText will be start,when i again press button same thing will be happened with 3rd EdtiText.NOw this code is working properly but when i press back button and again start it,its stopped working in 3rd EditText.The problem is sometimes the timer in 3rd EditText is not working(not displayed)..my code is as below:
mainActivity.java
package com.example.timerdemo2;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import org.w3c.dom.Text;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText et1,et2,et3;
TextView tv;
public int i=0;
long starttime = 0;
long lasttime,lasttime1;
final Handler handler = new Handler();
Handler h2 = new Handler();
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
Runnable run = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
int minutes = (seconds%3600)/60;
int hours = seconds / 3600;
seconds = seconds % 60;
et1.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
// et2.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
// et3.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
h2.postDelayed(this, 500);
}
};
class firstTask extends TimerTask {
public void run() {
handler.sendEmptyMessage(0);
}
};
class secondTask extends TimerTask{
#Override
public void run() {
// TODO Auto-generated method stub
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - starttime;
int seconds = (int)(millis/1000);
int hours =seconds/3600;
int minutes = (seconds % 3600)/60;
seconds = seconds % 60;
et2.setText(String.format("%02d:%02d:%02d", hours,minutes,seconds));
}
});
}
}
class thirdTask extends TimerTask{
#Override
public void run() {
// TODO Auto-generated method stub
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - starttime;
int seconds = (int)(millis/1000);
int hours =seconds/3600;
int minutes = (seconds % 3600)/60;
seconds = seconds % 60;
et3.setText(String.format("%02d:%02d:%02d", hours,minutes,seconds));
h2.postDelayed(this, 500);
}
});
}
}
Timer timer = new Timer();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = this.getIntent().getExtras();
String title = bundle.getString("title");
tv = (TextView)findViewById(R.id.projectTitle);
tv.setText(title);
et1= (EditText)findViewById(R.id.timeEdit1);
et2= (EditText)findViewById(R.id.timeEdit2);
et3= (EditText)findViewById(R.id.timeEdit3);
Button b = (Button)findViewById(R.id.btn);
b.setText("Start");
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Button b =(Button)v;
if(b.getText().equals("Stop")){
timer.cancel();
timer.purge();
h2.removeCallbacks(run);
Intent intent =new Intent(MainActivity.this,Timedetails.class);
Bundle bundle =new Bundle();
//Procedure for Showing time stamps on another page
String a = et1.getText().toString();
String b1 = et2.getText().toString();
String c = et3.getText().toString();
String t = tv.getText().toString();
intent.putExtra("titl1",t);
startActivity(intent);
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
try{
bundle.putString("t1", a);
bundle.putString("t2", b1);
bundle.putString("t3", c);
Date date1 = (Date) format.parse(a);
Date date2 = (Date) format.parse(b1);
Date date3 = (Date) format.parse(c);
//time difference in milliseconds
long timeDiff = date2.getTime() - date1.getTime();
long timeDiff2 = date3.getTime() - date2.getTime();
//new date object with time difference
Date diffDate = new Date(timeDiff);
Date diffDate2 = new Date(timeDiff2);
long timeDiffSecs = timeDiff/1000;
String timeDiffString = timeDiffSecs/3600+":"+
(timeDiffSecs%3600)/60+":"+
(timeDiffSecs%3600)%60;
long timeDiffSecs1 = timeDiff2/1000;
String timeDiffString1 = timeDiffSecs1/3600+":"+
(timeDiffSecs1%3600)/60+":"+
(timeDiffSecs1%3600)%60;
//formatted date string
// String timeDiffString = format.format(diffDate);
//System.out.println("Time Diff = "+ timeDiffString );
bundle.putString("t1", a);
bundle.putString("t2", b1);
bundle.putString("t3", c);
bundle.putString("dif1", timeDiffString);
bundle.putString("dif2", timeDiffString1);
}
catch(Exception e){
e.printStackTrace();
}
intent.putExtras(bundle);
startActivity(intent);
b.setText("Next");
}
else if(b.getText().equals("Lap1"))
{
timer.schedule(new secondTask(),0, 500);
h2.removeCallbacks(run);
b.setText("lap2");
}
else if(b.getText().equals("lap2")){
timer.schedule(new thirdTask(), 0,500);
h2.removeCallbacks(run);
timer.cancel();
timer.purge();
b.setText("Stop");
}
else {
starttime = System.currentTimeMillis();
timer = new Timer();
timer.schedule(new firstTask(), 0,500);
// timer.schedule(new secondTask(), 0,500);
//timer.schedule(new thirdTask(), 0,500);
h2.postDelayed(run, 0);
b.setText("Lap1");
//long lastdown = System.currentTimeMillis();
}
}
});
}
}
MainActivity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/abs5"
android:orientation="vertical" >
<TextView
android:id="#+id/projectTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|center"
android:layout_marginTop="5dp"
android:text="Project Title"
android:textColor="#CCCCCC"
android:textSize= "40dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:text="Timing Point1"
android:textSize="20dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#CCCCCC" />
<EditText
android:id="#+id/timeEdit1"
android:layout_width="172dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:background="#FFFFFF"
android:editable="false"
android:filterTouchesWhenObscured="false"
android:focusable="false" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Timing Point2"
android:textColor="#CCCCCC"
android:textSize="20dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/timeEdit2"
android:layout_width="172dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:focusable="false"
android:filterTouchesWhenObscured="false"
android:background="#FFFFFF"
android:editable="false" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:text="Timing Point3"
android:textColor="#CCCCCC"
android:textSize="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/timeEdit3"
android:layout_width="172dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:background="#FFFFFF"
android:editable="false" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:orientation="horizontal" >
<Button
android:id="#+id/btn"
android:layout_width="129dp"
android:layout_height="64dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="110dp"
android:layout_marginTop="10dp"
android:background="#drawable/aqa"
android:textColor="#FFFFFF"
android:textSize="30dp" />
</LinearLayout>
</LinearLayout>
Please help me for this as fast ...really thanking you.....hav a gud tym
Look at this code in your lap2 handler:
timer.schedule(new thirdTask(), 0,500);
h2.removeCallbacks(run);
timer.cancel();
timer.purge();
b.setText("Stop");
You schedule a task and cancel the timer immediately afterwards.
I would suggest that you get rid of the Timer and just use the Handler.postDelayed() method, as you have done already for the time updates and to start the update of the first field:
h2.postDelayed(run, 0);
Use the same method to start the updates for second and third fields. You don't need the Timer and TimerTask instances at all.
Also, why do you need two handlers (handler, and h2)?
This is what I have so far.. it just starts when the application is opened:
package com.android.countdown;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.TextView;
public class countdown extends Activity {
TextView mTextField;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextField = (TextView) findViewById(R.id.timer1);
new CountDownTimer(100000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("Seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("Finished");
}
}.start();
}
}
I know that I need to call start() inside a button procedure. However, if I move the .start() from where it's at the new CountDownTimer(100000 , 1000) { gets an error.
Well... maybe you need to first understand how Java and programming work. Then, you can try to do something like this:
CountDownTimer aCounter = new CountDownTimer(100000 , 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("Seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("Finished");
}
};
aCounter.start();
You can do it like this to make a thing what you want. Here is the Java code:
package com.example.smartbroashad.countdowntimer;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView timing;
TextView status;
int workingornot=1;
//running
public void startmeplease(View view)
{
if (workingornot==1)
{
workingornot=2;
//runned
countDownTimerofme.start();
Toast.makeText(this,"STARTED!",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this,"already started!",Toast.LENGTH_SHORT).show();
}
}
public void stopmeplease(View view)
{
countDownTimerofme.cancel();
status.setText("stoped!!");
workingornot=1;
}
public void settimeplease(View view)
{
}
CountDownTimer countDownTimerofme=new CountDownTimer(10000,1000) {
#Override
public void onTick(long l) {
timing.setText("time left: "+toString().valueOf(l/1000));
status.setText("started!!!");
}
#Override
public void onFinish() {
timing.setText("time left: 0");
status.setText("completed !!!!");
workingornot=1;//now able to run again
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timing=(TextView)findViewById(R.id.timer);
status=(TextView)findViewById(R.id.status);
}
}
Here is the 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"
android:background=" #8e44ad"
tools:context="com.example.smartbroashad.countdowntimer.MainActivity">
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="133dp"
android:layout_marginBottom="69dp"
android:layout_marginTop="16dp"
android:padding="20sp"
android:text="#string/countdown_timer_not_running"
android:textAlignment="center"
android:textAllCaps="true"
android:textColor="#2c3e50"
android:textSize="32sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="61dp"
android:layout_marginTop="32dp"
android:orientation="vertical"
app:layout_constraintBottom_toTopOf="#+id/linearLayout2"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/status">
<EditText
android:id="#+id/editText7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="time" />
<Button
android:id="#+id/settime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background=" #00aced"
android:text="set time"
android:onClick="settimeplease"
android:textAlignment="center"
android:textAllCaps="true"
android:textColor="#2c3e50"
android:textSize="32sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="48dp"
android:layout_marginTop="32dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearLayout">
<TextView
android:id="#+id/timer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/running"
android:textAlignment="center"
android:textAllCaps="true"
android:textColor="#2c3e50"
android:textSize="32sp"
android:textStyle="bold"
tools:text="#string/running" />
<Button
android:id="#+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background=" #64D448"
android:text="start"
android:onClick="startmeplease"
android:textAlignment="center"
android:textAllCaps="true"
android:textColor="#2c3e50"
android:textSize="32sp"
android:textStyle="bold" />
<Button
android:id="#+id/stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background=" #bb0000"
android:text="stop"
android:onClick="stopmeplease"
android:textAlignment="center"
android:textAllCaps="true"
android:textColor="#ffffff"
android:textSize="32sp"
android:textStyle="bold" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
CountDownTimer timer;
Start.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
timer= new CountDownTimer(3000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
time.setText(String.valueOf(count));
count++;
}
#Override
public void onFinish() {
time.setText("Finish");
}
};
timer.start();
}
});
Stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer.cancel();
}
});