When I click the button my app crashes and I have no idea why. I've looked up my code a lot of times but can't seem to find any "major flaws". The purpose of the app is just clicking the button twice as fast as possible and it displays the amount of time needed from the first tap to the second tap. Some sort of reaction thing. I used a timer because I didn't know what else to use.
(Value of start time) - (value of current timer) = (time between first and second click).
<?xml version="1.0" encoding="utf-8"?>
<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"
android:background="#000000"
tools:context="com.keklabs.reactiontimer.MainActivity">
<TextView
android:id="#+id/scoreText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="78dp"
android:text="Click below to start!"
android:textColor="#39FF14"
android:textSize="30dp" />
<Button
android:id="#+id/startStopButton"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#000000"
android:text="Start / Stop"
android:textSize="25dp"
android:textColor="#39FF14" />
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
private final long startTime = 0;
private final long interval = 100;
private boolean buttonClicked;
private Button startStopButton;
private TextView scoreText;
CountDownTimer timer = new CountDownTimer(30000, 100) {
#Override
public void onTick(long millisUntilFinished) {
scoreText.setText("kek"); //displayed text is value of starttime (30000) - current value of timer,
} //some sort of reaction game thing
#Override
public void onFinish() {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView scoreText = (TextView) findViewById(R.id.scoreText);
Button startStopButton = (Button) findViewById(R.id.startStopButton);
startStopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!buttonClicked) {
timer.start();
buttonClicked = true;
}
else {
timer.cancel();
buttonClicked = false;
}
}
});
}
}
EDIT
How do i do it the right way in the line scoreText.setText(startTime - millisUntilFinished); to display startTime-current timer value?
CountDownTimer timer = new CountDownTimer(startTime, interval) {
#Override
public void onTick(long millisUntilFinished) {
scoreText.setText(startTime - millisUntilFinished);
}
#Override
public void onFinish() {
}
};
Actually, you are declaring your TextView scoreText twice. One gloabally and other locally. You can replace TextView scoreText = (TextView) findViewById(R.id.scoreText);
to scoreText = (TextView) findViewById(R.id.scoreText);
in your onCreate()
Related
creating a water remainder app and stuck on this for two days. there are 3 buttons to 15min, 30min, 60min user can click any one of this button then by clicking on Start Remainder button application will generate notification reminders ("Time to Drink Water") for every 15,30 or 60 min based on selected button. On click Stop Reminder button all reminders will end. am new to android trying my best and i hope stackoverflow community will help.
waterRemainder.java
public class waterRemainder extends AppCompatActivity implements View.OnClickListener {
Button min15, min30, min60, rstart, rstop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_water_remainder);
min15 = (Button) findViewById(R.id.min15);
min15.setOnClickListener(this);
min30 = (Button) findViewById(R.id.min30);
min30.setOnClickListener(this);
min60 = (Button) findViewById(R.id.min60);
min60.setOnClickListener(this);
rstart = (Button) findViewById(R.id.rstart);
rstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StartRemainder();
}
});
rstop = (Button) findViewById(R.id.rstop);
rstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StopRemainder();
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.min15:
SetRemainder(15);
case R.id.min30:
SetRemainder(30);
case R.id.min60:
SetRemainder(60);
}
}
public void SetRemainder(int minutes){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE,5);
}
public void StartRemainder(){
NotificationCompat.Builder builder = new NotificationCompat.Builder(waterRemainder.this,"My Notification")
.setContentTitle("New Notification")
.setContentText("its working")
.setSmallIcon(R.drawable.ic_message)
.setAutoCancel(true);
}
public void StopRemainder(){
}
}
activity_water_remainder.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:background="#drawable/main_header_selector"
tools:context=".waterRemainder">
<Button
android:id="#+id/min15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="15 Min"
android:layout_above="#+id/min30"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp"/>
<Button
android:id="#+id/min30"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="30 Min"
android:layout_above="#+id/min60"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp"/>
<Button
android:id="#+id/min60"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="60 Min"
android:layout_centerInParent="true" />
<Button
android:id="#+id/rstart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="START
REMINDER"
android:layout_below="#+id/min60"
android:layout_toEndOf="#+id/min60"
android:layout_marginStart="20dp"
android:layout_marginTop="25dp"/>
<Button
android:id="#+id/rstop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP
REMINDER"
android:layout_below="#+id/min60"
android:layout_toStartOf="#+id/min60"
android:layout_marginEnd="20dp"
android:layout_marginTop="25dp"/>
</RelativeLayout>
In SetRemainder function do the following:
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//here you can show notification method
}
}, delay, period);
}
where delay is the amount of time in milliseconds before first execution.. In your case set it to 0 and period is the amount of time in milliseconds between subsequent executions which in your case will be the 'minutes' variable.
And write timer.cancel(); in the stop method to cancel the timer.
sorry for annoying you but i am in my first step in android programming and need your support
the question is,
i want to change between photos using next and previous Button
i have 3 photos in an array
and 2 button (next and previous )
put when i started my app. i should press next button twice to change the photo
also in previous i should press it twice to change back
hope someone help me to improve the code down
public class SabahList extends AppCompatActivity {
ImageView img;
int[] mario = new int[]{R.drawable.image_a,R.drawable.image_b,R.drawable.image_c};
int n =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sabah_list);
img= (ImageView)findViewById(R.id.imageView2);
}
public void btu_next(View view) {
img.setImageResource(mario[n]);
if(n<2)
n++;
}
public void btu_prev(View view) {
img.setImageResource(mario[n]);
if(n>0)
n--;
}
}
Here is your logic problem. Your button's function command them set resource first, then increase/decease value, therefore when you click the second time, it will be set as previous increasingly/decreasingly.
public void btu_next(View view) {
if(n < 2)
n++;
img.setImageResource(mario[n]);
}
This answer may helpful to you if you are using normal array added images from drawable
//Your xml like this
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.devobal.quitchet.SabahList"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/previous"
android:text="previous"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/next"
android:text="next"/>
</LinearLayout>
<ImageView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
//And your Activity like this
public class SabahList extends AppCompatActivity {
ImageView imageView2;
Button previous,next;
int i=0;
private int[] textureArrayWin = {R.drawable.star1,R.drawable.star2, R.drawable.star3,};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sabah_list);
imageView2 = (ImageView)findViewById(R.id.imageView2);
previous = (Button)findViewById(R.id.previous);
next = (Button)findViewById(R.id.next);
if(i==0){
previous.setVisibility(View.GONE);
}
if (i==2){
next.setVisibility(View.GONE);
}
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageView2.setImageResource(textureArrayWin[i]);
i--;
if(i==0){
previous.setVisibility(View.GONE);} else{ previous.setVisibility(View.VISIBLE);}
if (i==2){
next.setVisibility(View.GONE);
} else{next.setVisibility(View.VISIBLE)}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if you are loading from bitmap
imageView2.setImageResource(textureArrayWin[i]);
i++;
if(i==0){
previous.setVisibility(View.GONE); } else {previous.setVisibility(View.VISIBLE); }
if (i==2){
next.setVisibility(View.GONE);
} else{next.setVisibility(View.VISIBLE)}
}
});
}
}
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();
I have written a program in which i am using Timer and controlling that timer using Toggle states,
Like: My Toggle's default state is OFF, once i make changes in toggle state from OFF to ON TIMER starts, and when i again change to OFF it stops the timer as per requirement.
But problem starts when my Timer is ON and I switch to other activity and then again come back to Toggle activity and then do changes in toggle state from ON to OFF - it still runs Timer...
ToggleActivity.java:
public class ToggleActivity extends Activity implements OnCheckedChangeListener {
ToggleButton toggleButton;
TextView text;
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
Button btnSwitchActivity;
boolean toggleState;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toggle);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
text = (TextView) findViewById(R.id.textView1);
btnSwitchActivity = (Button) findViewById(R.id.btnSwitchActivity);
sharedPreferences = getApplicationContext().getSharedPreferences("toggleState",0);
toggleButton.setOnCheckedChangeListener(this);
btnSwitchActivity.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intentSwitchActivity = new Intent(ToggleActivity.this, SwitchActivity.class);
startActivity(intentSwitchActivity);
}
});
}
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
if(isChecked)
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("toggleState", true);
editor.commit();
text.setText("ON");
startTimer();
} else
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("toggleState", false);
editor.commit();
text.setText("OFF");
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 1000, 5000);
}
public void stoptimertask(View v) {
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), strDate, duration);
toast.show();
}
});
}
};
}
public void onResume() {
super.onResume();
toggleState = sharedPreferences.getBoolean("toggleState", false);
Log.v("toggleState-onResume()", Boolean.toString(toggleState));
if (toggleState) {
toggleButton.setChecked(true);
} else {
toggleButton.setChecked(false);
}
}
}
SwitchActivity.java:
public class SwitchActivity extends Activity {
Button btnToggleActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch);
btnToggleActivity = (Button) findViewById(R.id.btnToggleActivity);
btnToggleActivity.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(SwitchActivity.this, ToggleActivity.class);
startActivity(intent);
/**
* if i use finish() instead of Intent to switch to ToggleActivity
* my Timer works fine
*/
// finish
}
});
}
}
activity_toggle.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:gravity="center"
android:background="#ffffff"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".ToggleActivity" >
<ToggleButton
android:id="#+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/toggle_selector"
android:checked="false"
android:text=""
android:textOff=""
android:textOn="" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:text="#string/string_toggle_off"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/btnSwitchActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/string_btn_switch"/>
</LinearLayout>
activity_switch.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#ffffff"
android:orientation="vertical" >
<Button
android:id="#+id/btnToggleActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/string_btn_goback"
/>
</LinearLayout>
You should probably save the state of the toggle button in the savedInstanceState bundle by overriding onSaveInstanceState.
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outstate.putBoolean("KEY", yourButton.isToggle())
}
And then you can access it by reading the savedInstanceState bundle given to you in onCreate of your activity or onCreateView/onViewCreated if you work in a fragment.
Hope this helps.
I'm creating a Reaction time Test app, with one button. I create this button in my first Class: ReactionTestActivity. Now I want to use it in my CountDownTimer, but how do I do this?
public class CDT extends CountDownTimer {
public CDT (long millisInFuture, long countDownInterval, ReactionTestActivity RAT){
super(millisInFuture, countDownInterval);
}
public void onFinish(){
button.setText("press");
}
#Override
public void onTick(long millisUntilFinished) {
}
}
You just created the class. Assuming you're doing Android, you need to do the rest of Android stuff:
public class TimerActivity extends Activity implements OnClickListener {
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private Button startB;
public TextView text;
private final long startTime = 30 * 1000;
private final long interval = 1 * 1000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
//NOTE: I don't know what you expect as the third parameter
countDownTimer = new CDT(startTime, interval, null);
text.setText(text.getText() + String.valueOf(startTime/1000));
}
#Override
public void onClick(View v) {
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("STOP");
} else {
countDownTimer.cancel();
timerHasStarted = false;
startB.setText("RESTART");
}
}
public class CDT extends CountDownTimer {
//your class definition that you wrote above.
}
}
Now you need the 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:orientation="vertical"
android:background="#drawable/bgi" >
<TextView
android:id="#+id/timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:paddingRight="10dip"
android:textSize="50dp" />
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Start" />
</RelativeLayout>
Source:
http://androidbite.blogspot.com/2012/11/android-count-down-timer-example.html