Created
August 29, 2017 08:58
-
-
Save ssaurel/cf646c6cf83b70a81eead24e27f33244 to your computer and use it in GitHub Desktop.
Main Activity of the Current Time to English Words tutorial on the SSaurel's Blog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ssaurel.wordsclock; | |
import android.os.Bundle; | |
import android.support.v7.app.AppCompatActivity; | |
import android.widget.TextView; | |
import java.util.Calendar; | |
import java.util.Date; | |
import java.util.Timer; | |
import java.util.TimerTask; | |
public class MainActivity extends AppCompatActivity { | |
// creating an array containing numbers from 1-29 in words | |
public static String words[] = { "", "One", "Two", "Three", "Four", "Five", | |
"Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", | |
"Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", | |
"Eighteen", "Nineteen", "Twenty", "Twenty one", | |
"Twenty two", "Twenty three", "Twenty four", "Twenty five", | |
"Twenty six", "Twenty seven", "Twenty eight", "Twenty nine" }; | |
private TextView time; | |
private Timer timer; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
time = (TextView) findViewById(R.id.time); | |
} | |
@Override | |
protected void onResume() { | |
super.onResume(); | |
timer = new Timer(); | |
timer.scheduleAtFixedRate(new TimerTask() { | |
@Override | |
public void run() { | |
final String timeInWords = currentTimeInWords(); | |
runOnUiThread(new Runnable() { | |
@Override | |
public void run() { | |
time.setText(timeInWords); | |
} | |
}); | |
} | |
}, 0, 1000); | |
} | |
@Override | |
protected void onPause() { | |
super.onPause(); | |
timer.cancel(); | |
} | |
public static String currentTimeInWords() { | |
Date d = new Date(); | |
Calendar c = Calendar.getInstance(); | |
c.setTime(d); | |
int h = c.get(Calendar.HOUR); | |
int m = c.get(Calendar.MINUTE); | |
String plu, a; | |
if (m == 1 || m == 59) | |
plu = "Minute"; | |
else | |
plu = "Minutes"; | |
if (h == 12) | |
a = words[1]; // storing 'one' when hour is 12 | |
else | |
a = words[h + 1]; // if hour is not 12, then storing in words, | |
if (m == 0) | |
return words[h] + " O' clock"; | |
else if (m == 15) | |
return "Quarter past " + words[h]; | |
else if (m == 30) | |
return "Half past " + words[h]; | |
else if (m == 45) | |
return "Quarter to " + a; | |
else if (m < 30) // condition for minutes between 1-29 | |
return words[m] + " " + plu + " past " + words[h]; | |
else | |
// condition for minutes between 31-59 | |
return words[60 - m] + " " + plu + " to " + a; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment