Test the current time does it match between two values? - java

I want to test current time.
Is it the same between the two times?
-With the note, I've already done a job
function to enter the start time
and the time to end.
Now i want to complete the special function.
i'm testing this entry value between the two times.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int hourStart = 5;
int minuteStart = 30;
String PMAMStart="AM";
int hourEnd = 6;
int minuteEnd = 30;
String PMAMEnd="AM";
boolean checkTime= checkCurrentTimeBetweenTowVlue(hourStart,minuteStart,PMAMStart,hourEnd,minuteEnd,PMAMEnd);
}
private boolean checkCurrentTimeBetweenTowVlue(int hStart,int mStart,String ampmStart,int hEnd,int mEnd,String ampmEnd){
Calendar cal = Calendar.getInstance();
return false;
}
}

In your case, you can set the individual calendar fields such as AM_PM, Hour, and Minute for both start and end dates, convert the time to minutes, and then find the difference between the times. Here is the solution:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int hourStart = 5;
int minuteStart = 30;
String PMAMStart="AM";
int hourEnd = 6;
int minuteEnd = 30;
String PMAMEnd="AM";
boolean checkTime= checkCurrentTimeBetweenTwoValues(hourStart,minuteStart,PMAMStart,hourEnd,minuteEnd,PMAMEnd);
if (checkTime) {
System.out.println("Time is Same");
} else {
System.out.println("Time is not Same");
}
}
private boolean checkCurrentTimeBetweenTwoValues(int hStart,int mStart,String ampmStart,int hEnd,int mEnd,String ampmEnd){
Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
if (ampmStart.equalsIgnoreCase("AM")) {
startCalendar.set(Calendar.AM_PM, 0);
} else {
startCalendar.set(Calendar.AM_PM, 1);
}
startCalendar.setTimeZone(TimeZone.getDefault());
startCalendar.set(Calendar.HOUR, hStart);
startCalendar.set(Calendar.MINUTE, mStart);
if (ampmEnd.equalsIgnoreCase("AM")) {
endCalendar.set(Calendar.AM_PM, 0);
} else {
endCalendar.set(Calendar.AM_PM, 1);
}
endCalendar.setTimeZone(TimeZone.getDefault());
endCalendar.set(Calendar.HOUR, hEnd);
endCalendar.set(Calendar.MINUTE, mEnd);
long timeDifference = TimeUnit.MILLISECONDS.toMinutes(
Math.abs(endCalendar.getTimeInMillis() - startCalendar.getTimeInMillis()));
System.out.println(("Time Difference: " + timeDifference));
return (timeDifference == 0);
}
}
You can also use TimeUnit.MILLISECONDS.toSeconds to check for Seconds but for that, you need to set the Seconds component of the Calendar instance.
Regards,
AJ

If you can use Java 8 (beginning with API level 26 in Android) or if you are willing / able / allowed to import a very useful library that enables java.time support to lower API levels, then the following might be a neat solution:
public static boolean isNowBetween(int startHour, int startMinute, int endHour, int endMinute) {
LocalTime start = LocalTime.of(startHour, startMinute);
LocalTime end = LocalTime.of(endHour, endMinute);
LocalTime now = LocalTime.now();
return now.isAfter(start) && now.isBefore(end);
}

Get current minutes and hours from cal object. Convert start, end, current time into minutes, then it will be easy to compare.
private boolean checkCurrentTimeBetweenTowVlue(int hStart,int mStart,String ampmStart,int hEnd,int mEnd,String ampmEnd){
Calendar cal = Calendar.getInstance();
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
if(ampmStart.equals("PM")){
hStart += 12;
}
int minutes_start = hStart*60 + mStart;
if(ampmEnd.equals("PM")){
hEnd += 12;
}
int minutes_end = hEnd*60 + mEnd;
int minutes_curr = hours*60 + minutes;
if(minutes_curr>minutes_start && minutes_curr<minutes_end){
return true;
}
return false;
}

Related

Timepicker android interval

I have a TimePicker with an interval of 30 minutes. When I open up a custom dialog with this picker it works well and it shows me 2 choices correctly (0, 30) in the minutes spinner. But, when I confirm and I come back to the activity it shows me a wrong result like: 10:01 instead 10:30. That's the method I use to set the interval
public static void setTimePickerInterval(TimePicker timePicker) {
try {
NumberPicker minutePicker = (NumberPicker) timePicker.findViewById(Resources.getSystem().getIdentifier("minute", "id", "android"));
minutePicker.setMinValue(0);
minutePicker.setMaxValue((60 / TIME_PICKER_INTERVAL) - 1);
List<String> displayedValues = new ArrayList<>();
for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
displayedValues.add(String.format("%02d", i));
}
minutePicker.setDisplayedValues(displayedValues.toArray(new String[0]));
} catch (Exception e) {
Log.e(TAG, "Exception: " + e);
}
}
TIME_PICKER_INTERVAL is set as 30. And that's what i wrote in the activity inside the method that open a custom dialog with the picker
// Get time picker object.
TimePicker timePicker = customView.findViewById(R.id.timePickerExample);
Utils.setTimePickerInterval(timePicker);
timePicker.setIs24HourView(true);
timePicker.setHour(hour);
timePicker.setMinute(minute);
dpStartDate.init(year, month, day, new DatePicker.OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker datePicker, int year, int month, int day) {
MainActivity.this.year = year;
MainActivity.this.month = month;
MainActivity.this.day = day;
}
});
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker timePicker, int hour, int minute) {
Log.i(TAG, "onTimeChanged: " + minute +" "+ hour);
MainActivity.this.hour = hour;
MainActivity.this.minute = minute;
}
});
Log.i(TAG, "onTimeChanged: " + minute +" "+ hour); shows what I'm setting. The hours are corrected, minutes not. It seems that instead shows "0, 30" it shows and select "0, 1". Any idea?

Implement Java method for test data [duplicate]

I'm trying to generate a random date of birth for people in my database using a Java program. How would I do this?
import java.util.GregorianCalendar;
public class RandomDateOfBirth {
public static void main(String[] args) {
GregorianCalendar gc = new GregorianCalendar();
int year = randBetween(1900, 2010);
gc.set(gc.YEAR, year);
int dayOfYear = randBetween(1, gc.getActualMaximum(gc.DAY_OF_YEAR));
gc.set(gc.DAY_OF_YEAR, dayOfYear);
System.out.println(gc.get(gc.YEAR) + "-" + (gc.get(gc.MONTH) + 1) + "-" + gc.get(gc.DAY_OF_MONTH));
}
public static int randBetween(int start, int end) {
return start + (int)Math.round(Math.random() * (end - start));
}
}
java.util.Date has a constructor that accepts milliseconds since The Epoch, and java.util.Random has a method that can give you a random number of milliseconds. You'll want to set a range for the random value depending on the range of DOBs that you want, but those should do it.
Very roughly:
Random rnd;
Date dt;
long ms;
// Get a new random instance, seeded from the clock
rnd = new Random();
// Get an Epoch value roughly between 1940 and 2010
// -946771200000L = January 1, 1940
// Add up to 70 years to it (using modulus on the next long)
ms = -946771200000L + (Math.abs(rnd.nextLong()) % (70L * 365 * 24 * 60 * 60 * 1000));
// Construct a date
dt = new Date(ms);
Snippet for a Java 8 based solution:
Random random = new Random();
int minDay = (int) LocalDate.of(1900, 1, 1).toEpochDay();
int maxDay = (int) LocalDate.of(2015, 1, 1).toEpochDay();
long randomDay = minDay + random.nextInt(maxDay - minDay);
LocalDate randomBirthDate = LocalDate.ofEpochDay(randomDay);
System.out.println(randomBirthDate);
Note: This generates a random date between 1Jan1900 (inclusive) and 1Jan2015 (exclusive).
Note: It is based on epoch days, i.e. days relative to 1Jan1970 (EPOCH) - positive meaning after EPOCH, negative meaning before EPOCH
You can also create a small utility class:
public class RandomDate {
private final LocalDate minDate;
private final LocalDate maxDate;
private final Random random;
public RandomDate(LocalDate minDate, LocalDate maxDate) {
this.minDate = minDate;
this.maxDate = maxDate;
this.random = new Random();
}
public LocalDate nextDate() {
int minDay = (int) minDate.toEpochDay();
int maxDay = (int) maxDate.toEpochDay();
long randomDay = minDay + random.nextInt(maxDay - minDay);
return LocalDate.ofEpochDay(randomDay);
}
#Override
public String toString() {
return "RandomDate{" +
"maxDate=" + maxDate +
", minDate=" + minDate +
'}';
}
}
and use it like this:
RandomDate rd = new RandomDate(LocalDate.of(1900, 1, 1), LocalDate.of(2010, 1, 1));
System.out.println(rd.nextDate());
System.out.println(rd.nextDate()); // birthdays ad infinitum
You need to define a random date, right?
A simple way of doing that is to generate a new Date object, using a long (time in milliseconds since 1st January, 1970) and substract a random long:
new Date(Math.abs(System.currentTimeMillis() - RandomUtils.nextLong()));
(RandomUtils is taken from Apache Commons Lang).
Of course, this is far to be a real random date (for example you will not get date before 1970), but I think it will be enough for your needs.
Otherwise, you can create your own date by using Calendar class:
int year = // generate a year between 1900 and 2010;
int dayOfYear = // generate a number between 1 and 365 (or 366 if you need to handle leap year);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, randomYear);
calendar.set(Calendar.DAY_OF_YEAR, dayOfYear);
Date randomDoB = calendar.getTime();
For Java8 -> Assumming the data of birth must be before current day:
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.Random;
public class RandomDate {
public static LocalDate randomBirthday() {
return LocalDate.now().minus(Period.ofDays((new Random().nextInt(365 * 70))));
}
public static void main(String[] args) {
System.out.println("randomDate: " + randomBirthday());
}
}
If you don't mind adding a new library to your code you can use MockNeat (disclaimer: I am one of the authors).
MockNeat mock = MockNeat.threadLocal();
// Generates a random date between [1970-1-1, NOW)
LocalDate localDate = mock.localDates().val();
System.out.println(localDate);
// Generates a random date in the past
// but beore 1987-1-30
LocalDate min = LocalDate.of(1987, 1, 30);
LocalDate past = mock.localDates().past(min).val();
System.out.println(past);
LocalDate max = LocalDate.of(2020, 1, 1);
LocalDate future = mock.localDates().future(max).val();
System.out.println(future);
// Generates a random date between 1989-1-1 and 1993-1-1
LocalDate start = LocalDate.of(1989, 1, 1);
LocalDate stop = LocalDate.of(1993, 1, 1);
LocalDate between = mock.localDates().between(start, stop).val();
System.out.println(between);
Generating random Date of Births:
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(randomDOB());
}
}
public static String randomDOB() {
int yyyy = random(1900, 2013);
int mm = random(1, 12);
int dd = 0; // will set it later depending on year and month
switch(mm) {
case 2:
if (isLeapYear(yyyy)) {
dd = random(1, 29);
} else {
dd = random(1, 28);
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
dd = random(1, 31);
break;
default:
dd = random(1, 30);
break;
}
String year = Integer.toString(yyyy);
String month = Integer.toString(mm);
String day = Integer.toString(dd);
if (mm < 10) {
month = "0" + mm;
}
if (dd < 10) {
day = "0" + dd;
}
return day + '/' + month + '/' + year;
}
public static int random(int lowerBound, int upperBound) {
return (lowerBound + (int) Math.round(Math.random()
* (upperBound - lowerBound)));
}
public static boolean isLeapYear(int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
int noOfDays = calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
if (noOfDays > 365) {
return true;
}
return false;
}
}
You can checkout randomizer for random data generation.This library helps to create random data from given Model class.Checkout below example code.
public class Person {
#DateValue( from = "01 Jan 1990",to = "31 Dec 2002" , customFormat = "dd MMM yyyy")
String dateOfBirth;
}
//Generate random 100 Person(Model Class) object
Generator<Person> generator = new Generator<>(Person.class);
List<Person> persons = generator.generate(100);
As there are many built in data generator is accessible using annotation,You also can build custom data generator.I suggest you to go through documentation provided on library page.
Look this method:
public static Date dateRandom(int initialYear, int lastYear) {
if (initialYear > lastYear) {
int year = lastYear;
lastYear = initialYear;
initialYear = year;
}
Calendar cInitialYear = Calendar.getInstance();
cInitialYear.set(Calendar.YEAR, 2015);
long offset = cInitialYear.getTimeInMillis();
Calendar cLastYear = Calendar.getInstance();
cLastYear.set(Calendar.YEAR, 2016);
long end = cLastYear.getTimeInMillis();
long diff = end - offset + 1;
Timestamp timestamp = new Timestamp(offset + (long) (Math.random() * diff));
return new Date(timestamp.getTime());
}
I think this will do the trick:
public static void main(String[] args) {
Date now = new Date();
long sixMonthsAgo = (now.getTime() - 15552000000l);
long today = now.getTime();
for(int i=0; i<10; i++) {
long ms = ThreadLocalRandom.current().nextLong(sixMonthsAgo, today);
Date date = new Date(ms);
System.out.println(date.toString());
}
}
If you don't mind a 3rd party library, the Utils library has a RandomDateUtils that generates random java.util.Dates and all the dates, times, instants, and durations from Java 8's date and time API
LocalDate birthDate = RandomDateUtils.randomPastLocalDate();
LocalDate today = LocalDate.now();
LocalDate under18YearsOld = RandomDateUtils.randomLocalDate(today.minus(18, YEARS), today);
LocalDate over18YearsOld = RandomDateUtils.randomLocalDateBefore(today.minus(18, YEARS));
It is in the Maven Central Repository at:
<dependency>
<groupId>com.github.rkumsher</groupId>
<artifactId>utils</artifactId>
<version>1.3</version>
</dependency>
simplest method:
public static LocalDate randomDateOfBirth() {
final int maxAge = 100 * 12 * 31;
return LocalDate.now().minusDays(new Random().nextInt(maxAge));
}
Using the original answer and adapting it to the new java.time.* api and adding ways to generate n random dates -- the function will return a List.
// RandomBirthday.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class RandomBirthday {
public static List<String> getRandomBirthday(int groupSize, int minYear, int maxYear) {
/** Given a group size, this method will return `n` random birthday
* between 1922-2022 where `n=groupSize`.
*
* #param groupSize the number of random birthday to return
* #param minYear the min year [lower bound]
* #param maxYear the max year [upper bound]
* #return a list of random birthday with format YYYY-MM-DD
*/
ArrayList<String> birthdays = new ArrayList<>();
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
for (int i = 0; i < groupSize; i++) {
LocalDate baseDate = LocalDate.now();
LocalDate baseYear = baseDate.withYear(ThreadLocalRandom.current().nextInt(minYear, maxYear));
int dayOfYear = ThreadLocalRandom.current().nextInt(1, baseYear.lengthOfYear());
LocalDate baseRandBirthday = baseYear.withDayOfYear(dayOfYear);
LocalDate randDate = LocalDate.of(
baseRandBirthday.getYear(),
baseRandBirthday.getMonth(),
baseRandBirthday.getDayOfMonth()
);
String formattedDate = dateFormat.format(randDate);
birthdays.add(formattedDate);
}
return birthdays;
}
public static void main(String[] args) {
// main method
List<String> bDay = getRandomBirthday(40, 1960, 2022);
System.out.println(bDay);
}
}
I am studying Scala and ended up Googling Java solutions for choosing a random date between range. I found this post super helpful and this is my final solution. Hope it can help future Scala and Java programmers.
import java.sql.Timestamp
def date_rand(ts_start_str:String = "2012-01-01 00:00:00", ts_end_str:String = "2015-01-01 00:00:00"): String = {
val ts_start = Timestamp.valueOf(ts_start_str).getTime()
val ts_end = Timestamp.valueOf(ts_end_str).getTime()
val diff = ts_end - ts_start
println(diff)
val ts_rand = new Timestamp(ts_start + (Random.nextFloat() * diff).toLong)
return ts_rand.toString
} //> date_rand: (ts_start_str: String, ts_end_str: String)String
println(date_rand()) //> 94694400000
//| 2012-10-28 18:21:13.216
println(date_rand("2001-01-01 00:00:00", "2001-01-01 00:00:00"))
//> 0
//| 2001-01-01 00:00:00.0
println(date_rand("2001-01-01 00:00:00", "2010-01-01 00:00:00"))
//> 283996800000
//| 2008-02-16 23:15:48.864 //> 2013-12-21 08:32:16.384
int num = 0;
char[] a={'a','b','c','d','e','f'};
String error = null;
try {
num = Integer.parseInt(request.getParameter("num"));
Random r = new Random();
long currentDate = new Date().getTime();
ArrayList<Student> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
String name = "";
for (int j = 0; j < 6; j++) {
name += a[r.nextInt(5)];
}
list.add(new Student(i + 1, name, r.nextBoolean(), new Date(Math.abs(r.nextLong() % currentDate))));
}
request.setAttribute("list", list);
request.setAttribute("num", num);
request.getRequestDispatcher("student.jsp").forward(request, response);
} catch (NumberFormatException e) {
error = "Please enter interger number";
request.setAttribute("error", error);
request.getRequestDispatcher("student.jsp").forward(request, response);
}

How to set limit to open an activity only specific time in a day in android programatically?

I am making game in which i want to set that a user can only play game in a days 3 time..
When he played 3 times in a days then a message will pop up that you have reached to your limit and can not play more..
Try below code, explanations are inside code:
public class MainActivity extends AppCompatActivity {
private int lastCheck = 0;
private SharedPreferences pref;
private SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
//GET THE LAST CHECKED DATE FROM SHARED PREFERENCES, WE ARE USING DAY OF A MONTH
lastCheck = pref.getInt("lastcheck", 0);
//GET THE NUMBER OF TIMES THE ACTIVITY WAS OPENED FROM SHARED PREFERENCES
int count = pref.getInt("count", 0);
// IF IT IS A NEW DAY START COUNTING FROM 0 AGAIN
if(isNewDay()){
count = 0;
}
// IF COUNT REACHES 5 CLOSE THE ACTIVITY. YOU CAN USE ANY OTHER MEANS TO BLOCK IT.
if (count >= 5){
finish();
}
else{
// ELSE INCREMENT COUNT AND SAVE IT IN THE SHARED PREFERENCES
count++;
editor.putInt("count", count);
editor.commit();
}
}
// GET THE CURRENT DAY IN THE MONTH AND COMPARE IT WITH THE LAST CHECKED
public boolean isNewDay() {
Date date = new Date();
int today = Integer.parseInt(DateFormat.format("dd", date).toString());
boolean ret = lastCheck == 0 || today > lastCheck;
lastCheck = today;
return ret;
}
}
private fun isNewDay(): Boolean {
val date = Date()
val today: Int = DateFormat.format("dd", date).toString().toInt()
val ret = lastCheck == 0 || today > lastCheck
lastCheck = today
sharedPreferenceHandler.setAlbumCreatedDate(lastCheck)
return ret
}
if(isNewDay()){
//do what you want
}

First three characters missing from string when send from android via bluetooth

When I send "M" String to the Device I call time function from where I make my String.
Code:
` mManButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
man = 1;
clearScreen();
mManButton.setBackgroundResource(R.color.button_pressed);
mStartButton.setBackgroundResource(R.color.button_default);
mCalButton.setBackgroundResource(R.color.button_default);
mTestButton.setBackgroundResource(R.color.button_default);
mLinearButtton.setBackgroundResource(R.color.button_default);
mAutoButton.setBackgroundResource(R.color.button_default);
// Send a message using content of the edit text widget
sendMessage("M");
time();
}
});`
Then the time() function is called.
Here if my day is Monday then the variable day is set to 1.
That means in this function I am creating a String which has Date Format values in it. This string starts from "A" and ends with "B".
Code :
private void time()
{
int day = 0;
Date now = new Date();
String sdf = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(now);
switch(sdf){
case ("Monday"):
day = 1;
break;
case("Tuesday"):
day = 2;
break;
case ("Wednesday"):
day = 3;
break;
case ("Thursday"):
day = 4;
break;
case("Friday"):
day = 5;
break;
case ("Saturday"):
day = 6;
break;
case("Sunday"):
day = 7;
break;
}
int mm = Calendar.getInstance().get(Calendar.MINUTE);
int HH = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
int dd = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
int MM = Calendar.getInstance().get(Calendar.MONTH)+1;
int yy = Calendar.getInstance().get(Calendar.YEAR)%100;
if(mm<10) {
String time1 = "A" + "0" + mm + HH + "0" + day + dd + MM + yy + "B"; //suppose time1 = A041303211216B
tv7.setText("Please Wait..");
int p = 0;
while (p < time1.length())
{
char zx = time1.charAt(p);
String xz = String.valueOf(zx);
sendMessage(xz);
p++;
}
}
else if(mm>=10) {
String time2 = "A" + mm + HH + "0" + day + dd + MM + yy + "B"; **//suppose time2 = A151303211216B**
tv7.setText("Please Wait..");
int k = 0;
while (k < time2.length())
{
char zx = time2.charAt(k);
String xz = String.valueOf(zx);
sendMessage(xz);
k++;
}
}
}
When the string is created I send each characters of the string to sendMessage().
Code :
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() !=
com.example.hasani.bluetoothterminal.BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
mStartButton.setBackgroundResource(R.color.button_default);
mCalButton.setBackgroundResource(R.color.button_default);
mTestButton.setBackgroundResource(R.color.button_default);
mManButton.setBackgroundResource(R.color.button_default);
mAutoButton.setBackgroundResource(R.color.button_default);
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
}
}
The write function.
Code :
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
The wite in ConnectedThread
Code :
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(com.example.hasani.bluetoothterminal.Constants.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
As there is a role of Handler in it.
The issue is when debugging step by step, each character is sent to the other Device and that device receives each and every string from "A" to "B", thus there is no problem.
But when i run My android app, after sending "M", the time() function is called and the String is sent but the first three characters of the string i.e; "Amm" is not received by the device.
I still don't understand what is causing the problem.
Please Help!. Will be appreciated. Thank You!
Ohkay wait!!! I got the solution. In case if someone go through the same kind of situation.
In my onClickListener I call my time() function after a 5 second delay using a second handler.
My onClickListener code is :
mManButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
man = 1;
linear = 0;
auto = 0;
cal = 0;
test = 0;
linear = 0;
clearScreen();
mManButton.setBackgroundResource(R.color.button_pressed);
mStartButton.setBackgroundResource(R.color.button_default);
mCalButton.setBackgroundResource(R.color.button_default);
mTestButton.setBackgroundResource(R.color.button_default);
mLinearButtton.setBackgroundResource(R.color.button_default);
mAutoButton.setBackgroundResource(R.color.button_default);
// Send a message using content of the edit text widget
sendMessage("M");
tv7.setText("Please wait....");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
time();
}
},5000);
}
});
My time() function is :
private void time() {
int day = 0;
Date now = new Date();
String sdf = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(now);
switch (sdf) {
case ("Monday"):
day = 1;
break;
case ("Tuesday"):
day = 2;
break;
case ("Wednesday"):
day = 3;
break;
case ("Thursday"):
day = 4;
break;
case ("Friday"):
day = 5;
break;
case ("Saturday"):
day = 6;
break;
case ("Sunday"):
day = 7;
break;
}
int mm = Calendar.getInstance().get(Calendar.MINUTE);
int HH = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
int dd = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
int MM = Calendar.getInstance().get(Calendar.MONTH)+1;
int yy = Calendar.getInstance().get(Calendar.YEAR)%100;
String A = "A";
String min = String.format("%02d",mm);
String hour = String.format("%02d",HH);
String d = String.format("%02d",day);
String date = String.format("%02d",dd);
String month = String.format("%02d",MM);
String year = String.format("%02d",yy);
String B = "B";
String time2 = A+min+hour+d+date+month+year+B;
sendMessage(time2);
}
Now i can receive correct data as I required. My application works like a charm.
To expand on my comment, the simplest way to handle waiting to connect would be thus. First, return success or failure from write():
public boolean write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) return false;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
return true;
}
Then in sendMessage(), replace mChatService.write(send); with:
while (!mChatService.write(send))
{
try {
Thread.sleep(10);
}
catch(InterruptedException ex) {
// Uncomment to just give up
//break;
}
}
This will wait another 10 milliseconds or so before trying to resend.
There's of course a lot of improvements to make like only allowing a few retries before giving up completely, etc.
On a related note, with the above change you can probably do:
sendMessage(time1);
instead of doing it a character at a time.
Finally, your time formatting can be simplified to:
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
SimpleDateFormat format = new SimpleDateFormat("mmHHcddMMYY");
String time = "A" + format1.format(date) + "B";
Or something like that. See this page for details.

Java representing time class

I want to represent time with my time class. I can't use get and set methods.Only I can use listed methods on the code.But it doesn't work.
It returns 0:0:0.
public int addHours(int hours)
{
if(hours>=0&&hours<=23)
{
return hours;
}
return 0;
}
public int addMinutes(int minutes)
{
if(minutes>=0&&minutes<=59)
{
return minutes;
}
return 0;
}
public int addSeconds(int seconds)
{
if(seconds>=0&&seconds<=59)
{
return seconds;
}
return 0;
}
public String showTime()
{
return hours+":"+minutes+":"+seconds;
}
}
your code does nothing.
you need to do something like this:
public void addHours( int hours ){
this.hours += hours; // add hours
this.hours %= 24; // roll over at 24 hours
}
public void addMinutes( int minutes ){
this.minutes += minutes; // add minutes
addHours(this.minutes/60); // carry over to hours
this.minutes %= 60; // roll over at 60 minutes
}
public void addSeconds( int seconds ){
this.seconds += seconds; // add seconds
addMinutes(seconds/60); // carry over to minutes
this.seconds %= 60; // roll over at 60 seconds
}
(it probably won't matter, but this is not thread safe at all)
but this is generally a bad idea. Java 8 has a beautiful time api, pre Java-8 there is the JodaTime library (which is actually the basis of the Java 8 time api). It seems what you want to do could benefit from LocalTime:
LocalTime t = LocalTime.of(13,50,27).addHours(1).addMinutes(1).addSeconds(1);
System.out.println(t.toString());
// prints 14:51:28
Use java.util.Calendar and java.text.SimpleDateFormat:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 0);
cal.add(Calendar.HOUR, 5);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(cal.getTime()));

Categories

Resources